munitoai 0.1.0b1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
munitoai/__init__.py ADDED
@@ -0,0 +1,23 @@
1
+ """The Munito SDK: sandbox lifecycle, commands, files, and remote Python functions."""
2
+
3
+ from munitoai.async_client import AsyncMunito
4
+ from munitoai.client import ApiError, Munito
5
+ from munitoai.functions import App, FunctionError, RemoteFunction, Run
6
+ from munitoai.models import CommandResult, FileEntry, Gpu, Sandbox, SandboxCommand
7
+ from munitoai.training import log_metrics
8
+
9
+ __all__ = [
10
+ "ApiError",
11
+ "App",
12
+ "AsyncMunito",
13
+ "CommandResult",
14
+ "FileEntry",
15
+ "FunctionError",
16
+ "Gpu",
17
+ "Munito",
18
+ "RemoteFunction",
19
+ "Run",
20
+ "Sandbox",
21
+ "SandboxCommand",
22
+ "log_metrics",
23
+ ]
@@ -0,0 +1,207 @@
1
+ """Async access to the same public sandbox contract."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any, Self, Unpack
6
+ from urllib.parse import quote
7
+
8
+ import httpx
9
+
10
+ from munitoai import headers as h
11
+ from munitoai.client import PREFIX, ApiError, _checked, _create_body, _event, _options, _path
12
+ from munitoai.models import CommandResult, FileEntry, Gpu, Sandbox, SandboxCommand
13
+ from munitoai.training import AsyncTraining
14
+
15
+ if TYPE_CHECKING:
16
+ import builtins
17
+ from collections.abc import AsyncIterator
18
+
19
+ from munitoai.options import CreateOptions, ExecOptions, ForkOptions
20
+
21
+
22
+ class AsyncMunito:
23
+ def __init__(
24
+ self,
25
+ api_key: str | None = None,
26
+ *,
27
+ region: str = "global",
28
+ base_url: str | None = None,
29
+ timeout: float = 60,
30
+ transport: httpx.AsyncBaseTransport | None = None,
31
+ ) -> None:
32
+ options = _options(api_key, region, base_url)
33
+ self.token = options["headers"][h.AUTHORIZATION][7:]
34
+ self.http = httpx.AsyncClient(**options, timeout=timeout, transport=transport, trust_env=False)
35
+ self.sandboxes = AsyncSandboxes(self)
36
+ self.training = AsyncTraining(self)
37
+
38
+ async def close(self) -> None:
39
+ await self.http.aclose()
40
+
41
+ async def __aenter__(self) -> Self:
42
+ return self
43
+
44
+ async def __aexit__(self, *args: object) -> None:
45
+ await self.close()
46
+
47
+ async def request(self, method: str, path: str, **kwargs: Any) -> Any: # noqa: ANN401 - HTTPX request options and JSON results
48
+ response = _checked(await self.http.request(method, path, **kwargs))
49
+ return response.json() if response.content else None
50
+
51
+
52
+ class AsyncSandboxes:
53
+ def __init__(self, client: AsyncMunito) -> None:
54
+ self._client = client
55
+
56
+ async def create(
57
+ self,
58
+ *,
59
+ gpu: Gpu | str | dict[str, Any] | None = None,
60
+ idempotency_key: str | None = None,
61
+ **options: Unpack[CreateOptions],
62
+ ) -> Sandbox:
63
+ headers = {h.IDEMPOTENCY_KEY: idempotency_key} if idempotency_key else {}
64
+ return Sandbox.model_validate(
65
+ await self._client.request(
66
+ "POST", PREFIX, headers=headers, json=_create_body(gpu, options, self._client.token)
67
+ )
68
+ )
69
+
70
+ async def get(self, sandbox_id: str) -> Sandbox:
71
+ return Sandbox.model_validate(await self._client.request("GET", _path(sandbox_id)))
72
+
73
+ async def list(self, *, status: str | None = None) -> AsyncIterator[Sandbox]:
74
+ params: dict[str, Any] = {"limit": 100}
75
+ if status:
76
+ params["status"] = status
77
+ while True:
78
+ page = await self._client.request("GET", PREFIX, params=params)
79
+ for row in page["data"]:
80
+ yield Sandbox.model_validate(row)
81
+ if not page.get("has_more"):
82
+ return
83
+ if not page["data"]:
84
+ raise ApiError(0, "invalid_page", "The sandbox list has no next cursor.")
85
+ params["after"] = page["data"][-1]["id"]
86
+
87
+ async def delete(self, sandbox_id: str) -> Sandbox:
88
+ return Sandbox.model_validate(await self._client.request("DELETE", _path(sandbox_id)))
89
+
90
+ async def pause(self, sandbox_id: str) -> Sandbox:
91
+ return Sandbox.model_validate(await self._client.request("POST", _path(sandbox_id, "/pause")))
92
+
93
+ async def resume(self, sandbox_id: str, *, timeout: int | None = None) -> Sandbox: # noqa: ASYNC109 - remote sandbox lifetime
94
+ return Sandbox.model_validate(
95
+ await self._client.request("POST", _path(sandbox_id, "/resume"), json={"timeout": timeout})
96
+ )
97
+
98
+ async def set_timeout(self, sandbox_id: str, timeout: int) -> Sandbox: # noqa: ASYNC109 - remote sandbox lifetime
99
+ return Sandbox.model_validate(
100
+ await self._client.request("POST", _path(sandbox_id, "/timeout"), json={"timeout": timeout})
101
+ )
102
+
103
+ async def fork(self, sandbox_id: str, *, count: int = 1, **options: Unpack[ForkOptions]) -> builtins.list[Sandbox]:
104
+ page = await self._client.request("POST", _path(sandbox_id, "/fork"), json={"count": count, **options})
105
+ return [Sandbox.model_validate(row) for row in page["data"]]
106
+
107
+ async def exec(
108
+ self, sandbox_id: str, command: str | builtins.list[str], **options: Unpack[ExecOptions]
109
+ ) -> CommandResult:
110
+ return CommandResult.model_validate(
111
+ await self._client.request(
112
+ "POST",
113
+ _path(sandbox_id, "/exec"),
114
+ json={**options, "command": command, "stream": False},
115
+ timeout=httpx.Timeout(60, connect=10, read=(options.get("timeout") or 3600) + 30),
116
+ )
117
+ )
118
+
119
+ async def exec_stream(
120
+ self, sandbox_id: str, command: str | builtins.list[str], **options: Unpack[ExecOptions]
121
+ ) -> AsyncIterator[dict[str, Any]]:
122
+ async with self._client.http.stream(
123
+ "POST",
124
+ _path(sandbox_id, "/exec"),
125
+ json={**options, "command": command, "stream": True},
126
+ timeout=httpx.Timeout(60, connect=10, read=(options.get("timeout") or 3600) + 30),
127
+ ) as response:
128
+ if not response.is_success:
129
+ await response.aread()
130
+ _checked(response)
131
+ ended = False
132
+ async for line in response.aiter_lines():
133
+ if line.strip():
134
+ event = _event(line)
135
+ ended = ended or event["type"] == "exit"
136
+ yield event
137
+ if not ended:
138
+ raise ApiError(0, "incomplete_stream", "The command stream ended without an exit event.")
139
+
140
+ async def read_file(self, sandbox_id: str, path: str) -> bytes:
141
+ return _checked(await self._client.http.get(_path(sandbox_id, "/files/content"), params={"path": path})).content
142
+
143
+ async def write_file(self, sandbox_id: str, path: str, content: str | bytes) -> FileEntry:
144
+ return FileEntry.model_validate(
145
+ await self._client.request(
146
+ "PUT",
147
+ _path(sandbox_id, "/files/content"),
148
+ params={"path": path},
149
+ content=content.encode() if isinstance(content, str) else content,
150
+ headers={h.CONTENT_TYPE: "application/octet-stream"},
151
+ )
152
+ )
153
+
154
+ async def list_files(self, sandbox_id: str, path: str = "/workspace") -> builtins.list[FileEntry]:
155
+ page = await self._client.request("GET", _path(sandbox_id, "/files"), params={"path": path})
156
+ return [FileEntry.model_validate(row) for row in page["data"]]
157
+
158
+ async def delete_file(self, sandbox_id: str, path: str, *, recursive: bool = False) -> None:
159
+ await self._client.request("DELETE", _path(sandbox_id, "/files"), params={"path": path, "recursive": recursive})
160
+
161
+ async def start_command(
162
+ self, sandbox_id: str, command: str | builtins.list[str], **options: Unpack[ExecOptions]
163
+ ) -> SandboxCommand:
164
+ return SandboxCommand.model_validate(
165
+ await self._client.request("POST", _path(sandbox_id, "/commands"), json={**options, "command": command})
166
+ )
167
+
168
+ async def get_command(
169
+ self, sandbox_id: str, command_id: str, *, stdout: int = 0, stderr: int = 0
170
+ ) -> SandboxCommand:
171
+ return SandboxCommand.model_validate(
172
+ await self._client.request(
173
+ "GET",
174
+ _path(sandbox_id, f"/commands/{quote(command_id, safe='')}"),
175
+ params={"stdout": stdout, "stderr": stderr},
176
+ )
177
+ )
178
+
179
+ async def list_commands(self, sandbox_id: str) -> builtins.list[SandboxCommand]:
180
+ return [
181
+ SandboxCommand.model_validate(row)
182
+ for row in (await self._client.request("GET", _path(sandbox_id, "/commands")))["data"]
183
+ ]
184
+
185
+ async def signal_command(self, sandbox_id: str, command_id: str, signal: int = 15) -> SandboxCommand:
186
+ return SandboxCommand.model_validate(
187
+ await self._client.request(
188
+ "POST", _path(sandbox_id, f"/commands/{quote(command_id, safe='')}/signal"), json={"signal": signal}
189
+ )
190
+ )
191
+
192
+ async def sign_port_url(self, sandbox_id: str, port: int, *, expires_in: int = 3600) -> dict[str, Any]:
193
+ return await self._client.request(
194
+ "POST", _path(sandbox_id, f"/ports/{port}/url"), json={"expires_in": expires_in}
195
+ )
196
+
197
+ async def delete_command(self, sandbox_id: str, command_id: str) -> None:
198
+ await self._client.request("DELETE", _path(sandbox_id, f"/commands/{quote(command_id, safe='')}"))
199
+
200
+ async def set_port(self, sandbox_id: str, port: int, *, public: bool) -> dict[str, Any]:
201
+ return await self._client.request("PUT", _path(sandbox_id, f"/ports/{port}"), json={"public": public})
202
+
203
+ async def get_ssh(self, sandbox_id: str) -> dict[str, Any]:
204
+ return await self._client.request("GET", _path(sandbox_id, "/ssh"))
205
+
206
+ async def create_ssh_access(self, sandbox_id: str) -> dict[str, Any]:
207
+ return await self._client.request("POST", _path(sandbox_id, "/ssh/access"), json={})
munitoai/client.py ADDED
@@ -0,0 +1,260 @@
1
+ """Authenticated clients for the public sandbox API. Mutations receive no automatic retry."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from typing import TYPE_CHECKING, Any, Self, Unpack
8
+ from urllib.parse import quote
9
+
10
+ import httpx
11
+
12
+ from munitoai import headers as h
13
+ from munitoai.models import CommandResult, FileEntry, Gpu, Sandbox, SandboxCommand, gpu_request
14
+ from munitoai.training import Training
15
+
16
+ if TYPE_CHECKING:
17
+ import builtins
18
+ from collections.abc import Iterator, Mapping
19
+
20
+ from munitoai.options import CreateOptions, ExecOptions, ForkOptions
21
+
22
+ REGIONS = {"global": "https://api.munito.ai", "eu": "https://api.eu.munito.ai", "us": "https://api.us.munito.ai"}
23
+ PREFIX = "/sandboxes/v1/sandboxes"
24
+
25
+
26
+ class ApiError(RuntimeError):
27
+ def __init__(self, status: int, code: str, message: str, request_id: str | None = None) -> None:
28
+ super().__init__(message)
29
+ self.status = status
30
+ self.code = code
31
+ self.request_id = request_id
32
+
33
+
34
+ def _checked(response: httpx.Response) -> httpx.Response:
35
+ if not response.is_success:
36
+ try:
37
+ body = response.json()
38
+ except ValueError:
39
+ body = {}
40
+ if not isinstance(body, dict):
41
+ body = {}
42
+ raise ApiError(
43
+ response.status_code,
44
+ str(body.get("code", response.status_code)),
45
+ str(body.get("detail") or body.get("title") or response.reason_phrase),
46
+ response.headers.get(h.REQUEST_ID),
47
+ )
48
+ return response
49
+
50
+
51
+ def _path(sandbox_id: str, suffix: str = "") -> str:
52
+ return f"{PREFIX}/{quote(sandbox_id, safe='')}{suffix}"
53
+
54
+
55
+ def _options(api_key: str | None, region: str, base_url: str | None) -> dict[str, Any]:
56
+ key = api_key or os.environ.get("MUNITO_API_KEY")
57
+ if not key:
58
+ raise ValueError("Set MUNITO_API_KEY or supply api_key.")
59
+ if base_url is None and region not in REGIONS:
60
+ raise ValueError("Select global, eu, or us, or supply base_url.")
61
+ return {"base_url": (base_url or REGIONS[region]).rstrip("/"), "headers": {h.AUTHORIZATION: f"Bearer {key}"}}
62
+
63
+
64
+ def _create_body(gpu: Gpu | str | dict[str, Any] | None, options: Mapping[str, Any], token: str) -> dict[str, Any]:
65
+ body = dict(options)
66
+ if gpu is not None:
67
+ body["gpu"] = gpu_request(gpu)
68
+ if body.get("agent") and body.get("provider", "munito") == "munito" and body.get("auth", "token") == "token":
69
+ body["env"] = {"MUNITO_API_KEY": token, **body.get("env", {})}
70
+ return body
71
+
72
+
73
+ def _event(line: str) -> dict[str, Any]:
74
+ body = json.loads(line)
75
+ if not isinstance(body, dict) or body.get("type") not in {"stdout", "stderr", "exit", "error"}:
76
+ raise ApiError(0, "invalid_stream", "The command returned an invalid event.")
77
+ if body["type"] == "error":
78
+ error = body.get("error") or {}
79
+ raise ApiError(0, error.get("code", "command_failed"), error.get("message", "The command failed."))
80
+ return body
81
+
82
+
83
+ class Munito:
84
+ def __init__(
85
+ self,
86
+ api_key: str | None = None,
87
+ *,
88
+ region: str = "global",
89
+ base_url: str | None = None,
90
+ timeout: float = 60,
91
+ transport: httpx.BaseTransport | None = None,
92
+ ) -> None:
93
+ options = _options(api_key, region, base_url)
94
+ self.token = options["headers"][h.AUTHORIZATION][7:]
95
+ self.http = httpx.Client(**options, timeout=timeout, transport=transport, trust_env=False)
96
+ self.sandboxes = Sandboxes(self)
97
+ self.training = Training(self)
98
+
99
+ def close(self) -> None:
100
+ self.http.close()
101
+
102
+ def __enter__(self) -> Self:
103
+ return self
104
+
105
+ def __exit__(self, *args: object) -> None:
106
+ self.close()
107
+
108
+ def request(self, method: str, path: str, **kwargs: Any) -> Any: # noqa: ANN401 - HTTPX request options and JSON results
109
+ response = _checked(self.http.request(method, path, **kwargs))
110
+ return response.json() if response.content else None
111
+
112
+
113
+ class Sandboxes:
114
+ def __init__(self, client: Munito) -> None:
115
+ self._client = client
116
+
117
+ def create(
118
+ self,
119
+ *,
120
+ gpu: Gpu | str | dict[str, Any] | None = None,
121
+ idempotency_key: str | None = None,
122
+ **options: Unpack[CreateOptions],
123
+ ) -> Sandbox:
124
+ headers = {h.IDEMPOTENCY_KEY: idempotency_key} if idempotency_key else {}
125
+ return Sandbox.model_validate(
126
+ self._client.request("POST", PREFIX, headers=headers, json=_create_body(gpu, options, self._client.token))
127
+ )
128
+
129
+ def get(self, sandbox_id: str) -> Sandbox:
130
+ return Sandbox.model_validate(self._client.request("GET", _path(sandbox_id)))
131
+
132
+ def list(self, *, status: str | None = None) -> Iterator[Sandbox]:
133
+ params: dict[str, Any] = {"limit": 100}
134
+ if status:
135
+ params["status"] = status
136
+ while True:
137
+ page = self._client.request("GET", PREFIX, params=params)
138
+ for row in page["data"]:
139
+ yield Sandbox.model_validate(row)
140
+ if not page.get("has_more"):
141
+ return
142
+ if not page["data"]:
143
+ raise ApiError(0, "invalid_page", "The sandbox list has no next cursor.")
144
+ params["after"] = page["data"][-1]["id"]
145
+
146
+ def delete(self, sandbox_id: str) -> Sandbox:
147
+ return Sandbox.model_validate(self._client.request("DELETE", _path(sandbox_id)))
148
+
149
+ def pause(self, sandbox_id: str) -> Sandbox:
150
+ return Sandbox.model_validate(self._client.request("POST", _path(sandbox_id, "/pause")))
151
+
152
+ def resume(self, sandbox_id: str, *, timeout: int | None = None) -> Sandbox:
153
+ return Sandbox.model_validate(
154
+ self._client.request("POST", _path(sandbox_id, "/resume"), json={"timeout": timeout})
155
+ )
156
+
157
+ def set_timeout(self, sandbox_id: str, timeout: int) -> Sandbox:
158
+ return Sandbox.model_validate(
159
+ self._client.request("POST", _path(sandbox_id, "/timeout"), json={"timeout": timeout})
160
+ )
161
+
162
+ def fork(self, sandbox_id: str, *, count: int = 1, **options: Unpack[ForkOptions]) -> builtins.list[Sandbox]:
163
+ page = self._client.request("POST", _path(sandbox_id, "/fork"), json={"count": count, **options})
164
+ return [Sandbox.model_validate(row) for row in page["data"]]
165
+
166
+ def exec(self, sandbox_id: str, command: str | builtins.list[str], **options: Unpack[ExecOptions]) -> CommandResult:
167
+ return CommandResult.model_validate(
168
+ self._client.request(
169
+ "POST",
170
+ _path(sandbox_id, "/exec"),
171
+ json={**options, "command": command, "stream": False},
172
+ timeout=httpx.Timeout(60, connect=10, read=(options.get("timeout") or 3600) + 30),
173
+ )
174
+ )
175
+
176
+ def exec_stream(
177
+ self, sandbox_id: str, command: str | builtins.list[str], **options: Unpack[ExecOptions]
178
+ ) -> Iterator[dict[str, Any]]:
179
+ with self._client.http.stream(
180
+ "POST",
181
+ _path(sandbox_id, "/exec"),
182
+ json={**options, "command": command, "stream": True},
183
+ timeout=httpx.Timeout(60, connect=10, read=(options.get("timeout") or 3600) + 30),
184
+ ) as response:
185
+ if not response.is_success:
186
+ response.read()
187
+ _checked(response)
188
+ ended = False
189
+ for line in response.iter_lines():
190
+ if line.strip():
191
+ event = _event(line)
192
+ ended = ended or event["type"] == "exit"
193
+ yield event
194
+ if not ended:
195
+ raise ApiError(0, "incomplete_stream", "The command stream ended without an exit event.")
196
+
197
+ def read_file(self, sandbox_id: str, path: str) -> bytes:
198
+ return _checked(self._client.http.get(_path(sandbox_id, "/files/content"), params={"path": path})).content
199
+
200
+ def write_file(self, sandbox_id: str, path: str, content: str | bytes) -> FileEntry:
201
+ return FileEntry.model_validate(
202
+ self._client.request(
203
+ "PUT",
204
+ _path(sandbox_id, "/files/content"),
205
+ params={"path": path},
206
+ content=content.encode() if isinstance(content, str) else content,
207
+ headers={h.CONTENT_TYPE: "application/octet-stream"},
208
+ )
209
+ )
210
+
211
+ def list_files(self, sandbox_id: str, path: str = "/workspace") -> builtins.list[FileEntry]:
212
+ page = self._client.request("GET", _path(sandbox_id, "/files"), params={"path": path})
213
+ return [FileEntry.model_validate(row) for row in page["data"]]
214
+
215
+ def delete_file(self, sandbox_id: str, path: str, *, recursive: bool = False) -> None:
216
+ self._client.request("DELETE", _path(sandbox_id, "/files"), params={"path": path, "recursive": recursive})
217
+
218
+ def start_command(
219
+ self, sandbox_id: str, command: str | builtins.list[str], **options: Unpack[ExecOptions]
220
+ ) -> SandboxCommand:
221
+ return SandboxCommand.model_validate(
222
+ self._client.request("POST", _path(sandbox_id, "/commands"), json={**options, "command": command})
223
+ )
224
+
225
+ def get_command(self, sandbox_id: str, command_id: str, *, stdout: int = 0, stderr: int = 0) -> SandboxCommand:
226
+ return SandboxCommand.model_validate(
227
+ self._client.request(
228
+ "GET",
229
+ _path(sandbox_id, f"/commands/{quote(command_id, safe='')}"),
230
+ params={"stdout": stdout, "stderr": stderr},
231
+ )
232
+ )
233
+
234
+ def list_commands(self, sandbox_id: str) -> builtins.list[SandboxCommand]:
235
+ return [
236
+ SandboxCommand.model_validate(row)
237
+ for row in self._client.request("GET", _path(sandbox_id, "/commands"))["data"]
238
+ ]
239
+
240
+ def signal_command(self, sandbox_id: str, command_id: str, signal: int = 15) -> SandboxCommand:
241
+ return SandboxCommand.model_validate(
242
+ self._client.request(
243
+ "POST", _path(sandbox_id, f"/commands/{quote(command_id, safe='')}/signal"), json={"signal": signal}
244
+ )
245
+ )
246
+
247
+ def sign_port_url(self, sandbox_id: str, port: int, *, expires_in: int = 3600) -> dict[str, Any]:
248
+ return self._client.request("POST", _path(sandbox_id, f"/ports/{port}/url"), json={"expires_in": expires_in})
249
+
250
+ def delete_command(self, sandbox_id: str, command_id: str) -> None:
251
+ self._client.request("DELETE", _path(sandbox_id, f"/commands/{quote(command_id, safe='')}"))
252
+
253
+ def set_port(self, sandbox_id: str, port: int, *, public: bool) -> dict[str, Any]:
254
+ return self._client.request("PUT", _path(sandbox_id, f"/ports/{port}"), json={"public": public})
255
+
256
+ def get_ssh(self, sandbox_id: str) -> dict[str, Any]:
257
+ return self._client.request("GET", _path(sandbox_id, "/ssh"))
258
+
259
+ def create_ssh_access(self, sandbox_id: str) -> dict[str, Any]:
260
+ return self._client.request("POST", _path(sandbox_id, "/ssh/access"), json={})
munitoai/functions.py ADDED
@@ -0,0 +1,358 @@
1
+ """Remote Python functions on the normal sandbox and background command APIs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import contextlib
7
+ import hashlib
8
+ import inspect
9
+ import json
10
+ import textwrap
11
+ import time
12
+ import uuid
13
+ import warnings
14
+ from pathlib import Path, PurePosixPath
15
+ from typing import TYPE_CHECKING, Any, ParamSpec, Self, TypeVar, Unpack
16
+
17
+ import httpx
18
+
19
+ from munitoai.client import Munito
20
+ from munitoai.models import Gpu, Sandbox, SandboxCommand, gpu_request
21
+ from munitoai.training import log_metrics
22
+
23
+ if TYPE_CHECKING:
24
+ from collections.abc import Callable, Iterator
25
+
26
+ from munitoai.options import ClientOptions, CreateOptions
27
+
28
+ P = ParamSpec("P")
29
+ R = TypeVar("R")
30
+ ROOT = "/workspace/.munito-function"
31
+ ARTIFACTS = "/workspace/artifacts"
32
+
33
+
34
+ class FunctionError(RuntimeError):
35
+ def __init__(self, run_id: str, message: str) -> None:
36
+ super().__init__(message)
37
+ self.run_id = run_id
38
+
39
+
40
+ def _source(function: Callable[..., Any]) -> str:
41
+ if inspect.isgeneratorfunction(function) or inspect.isasyncgenfunction(function):
42
+ raise ValueError("A remote function must return one JSON result.")
43
+ closure = inspect.getclosurevars(function)
44
+ external = {
45
+ name: value for name, value in closure.globals.items() if name != "log_metrics" or value is not log_metrics
46
+ }
47
+ if external or closure.nonlocals:
48
+ names = sorted(external.keys() | closure.nonlocals.keys())
49
+ raise ValueError(
50
+ f"Import dependencies inside the remote function. Pass external values as arguments: {', '.join(names)}."
51
+ )
52
+ source = ast.parse(textwrap.dedent(inspect.getsource(function)))
53
+ node = source.body[0]
54
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
55
+ raise TypeError("Define a named Python function in a source file.")
56
+ node.name = "__munito_function"
57
+ node.type_params = []
58
+ node.decorator_list = []
59
+ node.returns = None
60
+ arguments = node.args
61
+ for argument in [*arguments.posonlyargs, *arguments.args, *arguments.kwonlyargs, arguments.vararg, arguments.kwarg]:
62
+ if argument is not None:
63
+ argument.annotation = None
64
+ arguments.defaults = []
65
+ arguments.kw_defaults = [None] * len(arguments.kwonlyargs)
66
+ return ast.unparse(source)
67
+
68
+
69
+ def _runner(source: str) -> str:
70
+ # Only the guest executes source. The client receives JSON, never executable serialized results.
71
+ return f"""from __future__ import annotations
72
+ import asyncio
73
+ import inspect
74
+ import json
75
+ from pathlib import Path
76
+
77
+ {inspect.getsource(log_metrics)}
78
+
79
+ {source}
80
+
81
+ if __name__ == "__main__":
82
+ payload = json.loads(Path("{ROOT}/arguments.json").read_text(encoding="utf-8"))
83
+ result = __munito_function(*payload["args"], **payload["kwargs"])
84
+ if inspect.isawaitable(result):
85
+ result = asyncio.run(result)
86
+ encoded = json.dumps(result, ensure_ascii=False, allow_nan=False)
87
+ temporary = Path("{ROOT}/result.tmp")
88
+ temporary.write_text(encoded, encoding="utf-8")
89
+ temporary.replace("{ROOT}/result.json")
90
+ """
91
+
92
+
93
+ class Run[R]:
94
+ def __init__(self, client: Munito, sandbox_id: str, command_id: str, *, training_id: str | None = None) -> None:
95
+ self._client = client
96
+ self.sandbox_id = sandbox_id
97
+ self.command_id = command_id
98
+ self.training_id = training_id
99
+
100
+ @property
101
+ def id(self) -> str:
102
+ return f"{self.sandbox_id}/{self.command_id}"
103
+
104
+ @classmethod
105
+ def from_id(cls, client: Munito, run_id: str, *, training_id: str | None = None) -> Run[Any]:
106
+ parts = run_id.split("/")
107
+ if len(parts) != 2 or not all(parts):
108
+ raise ValueError("A run ID contains the sandbox ID and command ID, separated by one slash.")
109
+ return cls(client, *parts, training_id=training_id)
110
+
111
+ def _capture(self, *, required: bool = True) -> None:
112
+ if self.training_id is not None:
113
+ try:
114
+ self._client.training.get(self.training_id)
115
+ except httpx.TransportError:
116
+ if required:
117
+ raise
118
+ warnings.warn(
119
+ "Training history is temporarily unavailable. The sandbox command remains independent.",
120
+ RuntimeWarning,
121
+ stacklevel=2,
122
+ )
123
+
124
+ def status(self) -> SandboxCommand:
125
+ state = self._client.sandboxes.get_command(self.sandbox_id, self.command_id)
126
+ self._capture(required=False)
127
+ return state
128
+
129
+ def result(self, *, timeout: float | None = None, poll_interval: float = 1) -> R:
130
+ if poll_interval <= 0 or (timeout is not None and timeout < 0):
131
+ raise ValueError("Use a positive poll interval and a nonnegative timeout.")
132
+ deadline = time.monotonic() + timeout if timeout is not None else float("inf")
133
+ while True:
134
+ state = self.status()
135
+ if state.status != "running":
136
+ if state.status != "exited" or state.exit_code != 0 or state.timed_out:
137
+ raise FunctionError(
138
+ self.id, state.stderr or f"The function ended with exit code {state.exit_code}."
139
+ )
140
+ return json.loads(self._client.sandboxes.read_file(self.sandbox_id, f"{ROOT}/result.json"))
141
+ remaining = deadline - time.monotonic()
142
+ if remaining <= 0:
143
+ raise TimeoutError(f"The function is still active: {self.id}. Use cancel() to stop it.")
144
+ time.sleep(min(poll_interval, remaining))
145
+
146
+ def logs(self, *, poll_interval: float = 1) -> Iterator[dict[str, str]]:
147
+ if poll_interval <= 0:
148
+ raise ValueError("Use a positive poll interval.")
149
+ stdout = stderr = 0
150
+ while True:
151
+ state = self._client.sandboxes.get_command(self.sandbox_id, self.command_id, stdout=stdout, stderr=stderr)
152
+ for kind in ("stdout", "stderr"):
153
+ if data := getattr(state, kind):
154
+ yield {"type": kind, "data": data}
155
+ self._capture(required=False)
156
+ stdout, stderr = state.stdout_bytes, state.stderr_bytes
157
+ if state.status != "running":
158
+ return
159
+ time.sleep(poll_interval)
160
+
161
+ def cancel(self) -> SandboxCommand:
162
+ if self.training_id is not None:
163
+ self._client.training.cancel(self.training_id)
164
+ return self.status()
165
+ return self._client.sandboxes.signal_command(self.sandbox_id, self.command_id, 15)
166
+
167
+ def download_artifacts(self, destination: str | Path) -> list[dict[str, Any]]:
168
+ root = Path(destination).resolve()
169
+ root.mkdir(parents=True, exist_ok=True)
170
+ manifest: list[dict[str, Any]] = []
171
+
172
+ def copy(remote: str, local: Path) -> None:
173
+ for entry in self._client.sandboxes.list_files(self.sandbox_id, remote):
174
+ if entry.name in {"", ".", ".."} or PurePosixPath(entry.name).name != entry.name or "\\" in entry.name:
175
+ raise ValueError("An artifact has an invalid file name.")
176
+ target = local / entry.name
177
+ if target.is_symlink() or not target.resolve().is_relative_to(root):
178
+ raise ValueError("An artifact path leaves the destination directory.")
179
+ source = f"{remote}/{entry.name}"
180
+ if entry.type == "directory":
181
+ target.mkdir(exist_ok=True)
182
+ copy(source, target)
183
+ elif entry.type == "file":
184
+ for _ in range(3):
185
+ data = self._client.sandboxes.read_file(self.sandbox_id, source)
186
+ if len(data) == entry.size:
187
+ break
188
+ else:
189
+ raise ValueError(
190
+ f"Artifact size mismatch for {source}: expected {entry.size}, got {len(data)}."
191
+ )
192
+ with target.open("xb") as output:
193
+ output.write(data)
194
+ manifest.append(
195
+ {
196
+ "path": target.relative_to(root).as_posix(),
197
+ "bytes": len(data),
198
+ "sha256": hashlib.sha256(data).hexdigest(),
199
+ }
200
+ )
201
+ else:
202
+ raise ValueError("Artifacts must be regular files or directories.")
203
+
204
+ copy(ARTIFACTS, root)
205
+ if self.training_id is not None:
206
+ self._client.training.artifacts(self.training_id, manifest)
207
+ return manifest
208
+
209
+ def close(self) -> None:
210
+ try:
211
+ self._capture()
212
+ finally:
213
+ self._client.sandboxes.delete(self.sandbox_id)
214
+ self._capture()
215
+
216
+ def __enter__(self) -> Run[R]:
217
+ return self
218
+
219
+ def __exit__(self, *args: object) -> None:
220
+ self.close()
221
+
222
+
223
+ class RemoteFunction[**P, R]:
224
+ def __init__(
225
+ self,
226
+ app: App,
227
+ function: Callable[P, R],
228
+ options: dict[str, Any],
229
+ artifacts: str | Path | None,
230
+ training: bool = False,
231
+ name: str | None = None,
232
+ ) -> None:
233
+ self._app = app
234
+ self._function = function
235
+ self._options = options
236
+ self._artifacts = artifacts
237
+ self._training = training
238
+ self._name = name or getattr(function, "__name__", "training")
239
+ self.__name__ = getattr(function, "__name__", "remote_function")
240
+ self.__doc__ = function.__doc__
241
+
242
+ def local(self, *args: P.args, **kwargs: P.kwargs) -> R:
243
+ return self._function(*args, **kwargs)
244
+
245
+ def spawn(self, *args: P.args, **kwargs: P.kwargs) -> Run[R]:
246
+ bound = inspect.signature(self._function).bind(*args, **kwargs)
247
+ bound.apply_defaults()
248
+ payload = json.dumps({"args": bound.args, "kwargs": bound.kwargs}, allow_nan=False)
249
+ source = _runner(_source(self._function))
250
+ client = self._app.client
251
+ options = dict(self._options)
252
+ duration = options.get("timeout", 3600)
253
+ if self._training:
254
+ client.training.list(limit=1)
255
+ sandbox = client.sandboxes.create(idempotency_key=uuid.uuid4().hex, **options)
256
+ try:
257
+ self._prepare(sandbox, payload, source)
258
+ except BaseException:
259
+ with contextlib.suppress(Exception):
260
+ client.sandboxes.delete(sandbox.id)
261
+ raise
262
+ try:
263
+ command = client.sandboxes.start_command(sandbox.id, ["python3", f"{ROOT}/run.py"], timeout=duration)
264
+ except Exception as exc:
265
+ # An ambiguous response must not launch the training code twice or delete its possible checkpoints.
266
+ raise FunctionError(
267
+ sandbox.id, f"The function start is unknown. Inspect commands in sandbox {sandbox.id}."
268
+ ) from exc
269
+ training_id = None
270
+ if self._training:
271
+ try:
272
+ record = client.training.create(name=self._name, sandbox_id=sandbox.id, command_id=command.id)
273
+ training_id = record["id"]
274
+ except Exception as exc:
275
+ raise FunctionError(
276
+ f"{sandbox.id}/{command.id}",
277
+ "The function started, but its training history could not be saved. Attach to its run ID.",
278
+ ) from exc
279
+ return Run(client, sandbox.id, command.id, training_id=training_id)
280
+
281
+ def _prepare(self, sandbox: Sandbox, payload: str, source: str) -> None:
282
+ client = self._app.client
283
+ while sandbox.status == "pending":
284
+ if time.time() >= sandbox.expires_at:
285
+ raise FunctionError(sandbox.id, "The sandbox expired before the function started.")
286
+ time.sleep(1)
287
+ sandbox = client.sandboxes.get(sandbox.id)
288
+ if sandbox.status != "running":
289
+ raise FunctionError(sandbox.id, "The sandbox failed before the function started.")
290
+ setup = client.sandboxes.exec(sandbox.id, ["mkdir", "-p", ROOT, ARTIFACTS])
291
+ if setup.exit_code:
292
+ raise FunctionError(sandbox.id, "The function workspace could not be prepared.")
293
+ client.sandboxes.write_file(sandbox.id, f"{ROOT}/arguments.json", payload)
294
+ client.sandboxes.write_file(sandbox.id, f"{ROOT}/run.py", source)
295
+
296
+ def remote(self, *args: P.args, **kwargs: P.kwargs) -> R:
297
+ run = self.spawn(*args, **kwargs)
298
+ try:
299
+ result = run.result()
300
+ except FunctionError:
301
+ raise
302
+ except KeyboardInterrupt:
303
+ with contextlib.suppress(Exception):
304
+ run.cancel()
305
+ run.close()
306
+ raise
307
+ except Exception as exc:
308
+ raise FunctionError(run.id, f"The result is unavailable. Attach to run {run.id} to inspect it.") from exc
309
+ if self._artifacts is not None:
310
+ try:
311
+ run.download_artifacts(self._artifacts)
312
+ except Exception as exc:
313
+ raise FunctionError(
314
+ run.id, f"Artifact export failed. Run {run.id} remains available until its timeout."
315
+ ) from exc
316
+ run.close()
317
+ return result
318
+
319
+
320
+ class App:
321
+ def __init__(self, client: Munito | None = None, **client_options: Unpack[ClientOptions]) -> None:
322
+ self._client = client
323
+ self._client_options = client_options
324
+ self._owns_client = client is None
325
+
326
+ @property
327
+ def client(self) -> Munito:
328
+ if self._client is None:
329
+ self._client = Munito(**self._client_options)
330
+ return self._client
331
+
332
+ def function(
333
+ self,
334
+ *,
335
+ gpu: Gpu | str | dict[str, Any] | None = None,
336
+ artifacts: str | Path | None = None,
337
+ training: bool = False,
338
+ name: str | None = None,
339
+ **options: Unpack[CreateOptions],
340
+ ) -> Callable[[Callable[P, R]], RemoteFunction[P, R]]:
341
+ resources: dict[str, Any] = dict(options)
342
+ if gpu is not None:
343
+ resources["gpu"] = gpu_request(gpu)
344
+
345
+ def decorate(function: Callable[P, R]) -> RemoteFunction[P, R]:
346
+ return RemoteFunction(self, function, resources, artifacts, training, name)
347
+
348
+ return decorate
349
+
350
+ def close(self) -> None:
351
+ if self._client is not None and self._owns_client:
352
+ self._client.close()
353
+
354
+ def __enter__(self) -> Self:
355
+ return self
356
+
357
+ def __exit__(self, *args: object) -> None:
358
+ self.close()
munitoai/headers.py ADDED
@@ -0,0 +1,6 @@
1
+ """Generated by tools.headers from the public header registry."""
2
+
3
+ AUTHORIZATION = "authorization"
4
+ CONTENT_TYPE = "content-type"
5
+ IDEMPOTENCY_KEY = "idempotency-key"
6
+ REQUEST_ID = "x-request-id"
munitoai/models.py ADDED
@@ -0,0 +1,76 @@
1
+ """Public sandbox results. Unknown response fields remain compatible with newer servers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Literal
6
+
7
+ from pydantic import BaseModel, ConfigDict, Field
8
+
9
+
10
+ class Gpu(BaseModel):
11
+ model_config = ConfigDict(extra="forbid")
12
+ type: Literal["L4"]
13
+ count: int = Field(default=1, ge=1, le=8, strict=True)
14
+
15
+
16
+ class CommandResult(BaseModel):
17
+ exit_code: int
18
+ stdout: str = ""
19
+ stderr: str = ""
20
+ duration_ms: int = 0
21
+ timed_out: bool = False
22
+ truncated: bool = False
23
+
24
+
25
+ class Sandbox(BaseModel):
26
+ id: str
27
+ status: Literal["pending", "running", "paused", "stopped", "failed"]
28
+ template: str = "base"
29
+ size: str = "default"
30
+ vcpus: int = 0
31
+ memory_mib: int = 0
32
+ disk_gib: int = 0
33
+ gpu: Gpu | None = None
34
+ internet: bool = False
35
+ persistent: bool = False
36
+ metadata: dict[str, str] = Field(default_factory=dict)
37
+ created_at: int = 0
38
+ expires_at: int = 0
39
+ started_at: int | None = None
40
+ ended_at: int | None = None
41
+ end_reason: str | None = None
42
+ command: CommandResult | None = None
43
+
44
+
45
+ class SandboxCommand(BaseModel):
46
+ id: str
47
+ command: list[str]
48
+ cwd: str
49
+ status: Literal["running", "exited", "failed"]
50
+ started_at: float
51
+ ended_at: float | None = None
52
+ exit_code: int | None = None
53
+ timed_out: bool = False
54
+ stdout: str = ""
55
+ stderr: str = ""
56
+ stdout_bytes: int = 0
57
+ stderr_bytes: int = 0
58
+ truncated: bool = False
59
+
60
+
61
+ class FileEntry(BaseModel):
62
+ name: str
63
+ path: str
64
+ type: Literal["file", "directory", "symlink", "other"]
65
+ size: int
66
+ mode: int = 0
67
+ modified_at: int = 0
68
+
69
+
70
+ def gpu_request(value: Gpu | str | dict[str, Any] | None) -> dict[str, Any] | None:
71
+ if value is None:
72
+ return None
73
+ if isinstance(value, str):
74
+ name, separator, count = value.partition(":")
75
+ value = {"type": name, "count": int(count) if separator else 1}
76
+ return Gpu.model_validate(value).model_dump()
munitoai/options.py ADDED
@@ -0,0 +1,51 @@
1
+ """Typed options shared by the synchronous and asynchronous clients."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, TypedDict
6
+
7
+ if TYPE_CHECKING:
8
+ import httpx
9
+
10
+
11
+ class ClientOptions(TypedDict, total=False):
12
+ api_key: str | None
13
+ region: str
14
+ base_url: str | None
15
+ timeout: float
16
+ transport: httpx.BaseTransport | None
17
+
18
+
19
+ class CreateOptions(TypedDict, total=False):
20
+ template: str
21
+ size: str
22
+ vcpus: int
23
+ memory_mib: int
24
+ disk_gib: int
25
+ internet: bool
26
+ persistent: bool
27
+ timeout: int
28
+ env: dict[str, str]
29
+ metadata: dict[str, str]
30
+ command: str | list[str]
31
+ ssh_keys: list[str]
32
+ public_ports: list[int]
33
+ hostname: str
34
+ networks: list[str]
35
+ agent: str
36
+ provider: str
37
+ auth: str
38
+ model: str
39
+
40
+
41
+ class ExecOptions(TypedDict, total=False):
42
+ cwd: str
43
+ env: dict[str, str]
44
+ timeout: int
45
+ stdin: str
46
+
47
+
48
+ class ForkOptions(TypedDict, total=False):
49
+ persistent: bool
50
+ timeout: int
51
+ metadata: dict[str, str]
munitoai/py.typed ADDED
File without changes
munitoai/training.py ADDED
@@ -0,0 +1,84 @@
1
+ """Internal training history. Artifact records describe exports to the SDK client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any
6
+ from urllib.parse import quote
7
+
8
+ if TYPE_CHECKING:
9
+ import builtins
10
+
11
+ from munitoai.async_client import AsyncMunito
12
+ from munitoai.client import Munito
13
+
14
+ PREFIX = "/sandboxes/v1/training-runs"
15
+
16
+
17
+ def log_metrics(values: dict[str, float], *, step: int) -> None:
18
+ """Report numeric metrics from a remote function without a guest SDK dependency."""
19
+ import json # noqa: PLC0415 - this helper is bundled into the guest script
20
+ import math # noqa: PLC0415
21
+ import re # noqa: PLC0415
22
+
23
+ if type(step) is not int or step < 0 or not 1 <= len(values) <= 32:
24
+ raise ValueError("Supply a nonnegative step and between 1 and 32 metrics.")
25
+ if any(
26
+ not re.fullmatch(r"[a-zA-Z][a-zA-Z0-9_./-]{0,63}", key)
27
+ or type(value) not in (int, float)
28
+ or not math.isfinite(value)
29
+ for key, value in values.items()
30
+ ):
31
+ raise ValueError("Metric names must be short identifiers. Metric values must be finite numbers.")
32
+ print("@@munito.metrics " + json.dumps({"step": step, "values": values}, allow_nan=False), flush=True)
33
+
34
+
35
+ class Training:
36
+ def __init__(self, client: Munito) -> None:
37
+ self._client = client
38
+
39
+ def list(self, *, limit: int = 20, after: str = "") -> dict[str, Any]:
40
+ return self._client.request("GET", PREFIX, params={"limit": limit, "after": after})
41
+
42
+ def create(self, *, name: str, sandbox_id: str, command_id: str) -> dict[str, Any]:
43
+ return self._client.request(
44
+ "POST", PREFIX, json={"name": name, "sandbox_id": sandbox_id, "command_id": command_id}
45
+ )
46
+
47
+ def get(self, run_id: str) -> dict[str, Any]:
48
+ return self._client.request("GET", f"{PREFIX}/{quote(run_id, safe='')}")
49
+
50
+ def cancel(self, run_id: str) -> dict[str, Any]:
51
+ return self._client.request("POST", f"{PREFIX}/{quote(run_id, safe='')}/cancel")
52
+
53
+ def artifacts(self, run_id: str, manifest: builtins.list[dict[str, Any]]) -> dict[str, Any]:
54
+ return self._client.request("PUT", f"{PREFIX}/{quote(run_id, safe='')}/artifacts", json={"artifacts": manifest})
55
+
56
+ def delete(self, run_id: str) -> None:
57
+ self._client.request("DELETE", f"{PREFIX}/{quote(run_id, safe='')}")
58
+
59
+
60
+ class AsyncTraining:
61
+ def __init__(self, client: AsyncMunito) -> None:
62
+ self._client = client
63
+
64
+ async def list(self, *, limit: int = 20, after: str = "") -> dict[str, Any]:
65
+ return await self._client.request("GET", PREFIX, params={"limit": limit, "after": after})
66
+
67
+ async def create(self, *, name: str, sandbox_id: str, command_id: str) -> dict[str, Any]:
68
+ return await self._client.request(
69
+ "POST", PREFIX, json={"name": name, "sandbox_id": sandbox_id, "command_id": command_id}
70
+ )
71
+
72
+ async def get(self, run_id: str) -> dict[str, Any]:
73
+ return await self._client.request("GET", f"{PREFIX}/{quote(run_id, safe='')}")
74
+
75
+ async def cancel(self, run_id: str) -> dict[str, Any]:
76
+ return await self._client.request("POST", f"{PREFIX}/{quote(run_id, safe='')}/cancel")
77
+
78
+ async def artifacts(self, run_id: str, manifest: builtins.list[dict[str, Any]]) -> dict[str, Any]:
79
+ return await self._client.request(
80
+ "PUT", f"{PREFIX}/{quote(run_id, safe='')}/artifacts", json={"artifacts": manifest}
81
+ )
82
+
83
+ async def delete(self, run_id: str) -> None:
84
+ await self._client.request("DELETE", f"{PREFIX}/{quote(run_id, safe='')}")
@@ -0,0 +1,164 @@
1
+ Metadata-Version: 2.5
2
+ Name: munitoai
3
+ Version: 0.1.0b1
4
+ Summary: The Munito Python SDK for sandboxes and remote GPU functions.
5
+ License-Expression: Apache-2.0
6
+ Requires-Python: >=3.12
7
+ Requires-Dist: httpx<1,>=0.28
8
+ Requires-Dist: pydantic<3,>=2.11
9
+ Description-Content-Type: text/markdown
10
+
11
+ # Munito Python SDK
12
+
13
+ The SDK uses the normal sandbox API. GPU requests require access to the L4 beta.
14
+ Python 3.12 or later is required. The package has no Munito server dependencies.
15
+ The public GPU sandbox guide links to the versioned beta wheel.
16
+
17
+ Install the package from a checkout:
18
+
19
+ ```sh
20
+ uv pip install ./python/packages/domain/munito/sdk
21
+ ```
22
+
23
+ Set `MUNITO_API_KEY` in the environment. Select `region="eu"`, `"us"`, or `"global"` when you create the client.
24
+
25
+ ## Sandboxes
26
+
27
+ ```python
28
+ from munitoai import Gpu, Munito
29
+
30
+ with Munito(region="eu") as client:
31
+ box = client.sandboxes.create(gpu=Gpu(type="L4", count=1), timeout=600)
32
+ try:
33
+ result = client.sandboxes.exec(
34
+ box.id,
35
+ ["python3", "-c", "import torch; print(torch.cuda.get_device_name(0))"],
36
+ )
37
+ print(result.stdout)
38
+ finally:
39
+ client.sandboxes.delete(box.id)
40
+ ```
41
+
42
+ `gpu="L4"` and `gpu="L4:2"` are shorthand for the same request object.
43
+ All GPUs belong to one host. A CPU request omits `gpu`.
44
+ Multiple GPUs do not parallelize a function automatically. Use the distributed launcher of your training framework when the code requires multiple processes.
45
+ The initial GPU runtime supports the base template, no Internet access, and an ephemeral workspace.
46
+ It does not support pause, resume, or snapshots. The workspace uses the sandbox's memory limit.
47
+
48
+ `AsyncMunito` has the same sandbox methods. Await its requests and use `async for` for lists and command streams.
49
+ Both clients preserve the API problem code and request ID in `ApiError`.
50
+ Neither client retries a mutation automatically. Use `idempotency_key` to repeat a create safely.
51
+
52
+ ## Remote Python functions
53
+
54
+ ```python
55
+ from munitoai import App
56
+
57
+ app = App(region="eu")
58
+
59
+ @app.function(gpu="L4", timeout=600)
60
+ def gpu_name():
61
+ import torch
62
+
63
+ assert torch.cuda.is_available()
64
+ return {"name": torch.cuda.get_device_name(0), "count": torch.cuda.device_count()}
65
+
66
+ if __name__ == "__main__":
67
+ print(gpu_name.remote())
68
+ app.close()
69
+ ```
70
+
71
+ The decorator marks a function. `.remote()` starts it and waits for its JSON result.
72
+ `.spawn()` returns a run handle. `.local()` calls the original function on the local machine.
73
+ Import dependencies inside the function. Pass external values as JSON arguments.
74
+ The SDK sends that function's source. It does not copy module globals, local credentials, or the project directory.
75
+ Dependencies must exist in the sandbox template. The decorator does not install packages or build images.
76
+ The function body must support the template's Python version.
77
+
78
+ ```python
79
+ run = gpu_name.spawn()
80
+ print(run.id)
81
+ for event in run.logs():
82
+ print(event["data"], end="")
83
+ print(run.result())
84
+ run.close()
85
+ ```
86
+
87
+ `Run.from_id(client, run_id)` attaches to the same background command after the local client disconnects.
88
+ `run.cancel()` sends SIGTERM. `run.close()` deletes the sandbox and releases its GPUs.
89
+ A result timeout leaves the remote command active. A failed function retains its sandbox until its timeout for inspection.
90
+ The run handle does not survive host loss. It does not provide automatic checkpoint recovery or a retry scheduler.
91
+
92
+ ## Training artifacts
93
+
94
+ Write checkpoints and metrics under `/workspace/artifacts`.
95
+ Call `run.download_artifacts(destination)` before `run.close()` to retain them locally.
96
+ The returned manifest contains each relative path, byte count, and SHA-256 hash.
97
+ The export rejects symlinks, path traversal, and an existing output file.
98
+ The API limits each file transfer to 100 MiB. Use smaller checkpoint shards.
99
+
100
+ Set `artifacts="./output"` on the decorator to export after a successful `.remote()` call, before sandbox deletion.
101
+ If export fails, the SDK retains the sandbox until its timeout and reports its run ID.
102
+ The local export survives sandbox deletion. It is not a shared volume or an object-store checkpoint.
103
+
104
+ Training code remains ordinary Python. Prepare data, train, evaluate the held-out data, and export checkpoints through these operations.
105
+ Pin the base model revision, dependency versions, data split, and evaluation settings in the artifact manifest.
106
+ GPU node loss or preemption requires a new sandbox and an explicit checkpoint restore.
107
+
108
+ ## TypeScript parity
109
+
110
+ | Operation | Python | TypeScript |
111
+ |---|---|---|
112
+ | Create, inspect, list, delete | `create`, `get`, `list`, `delete` | `create`, `get`, `list`, `delete` |
113
+ | CPU snapshot lifecycle | `pause`, `resume`, `fork` | `pause`, `resume`, `fork` |
114
+ | Lifetime | `set_timeout` | `setTimeout` |
115
+ | Commands and streams | `exec`, `exec_stream` | `exec`, `execStream` |
116
+ | Background commands | `start_command`, `get_command`, `list_commands` | `startCommand`, `getCommand`, `listCommands` |
117
+ | Stop and remove a command | `signal_command`, `delete_command` | `signalCommand`, `deleteCommand` |
118
+ | Binary files | `read_file`, `write_file` | `readFileBytes`, `writeFile` |
119
+ | File inventory | `list_files`, `delete_file` | `listFiles`, `deleteFile` |
120
+ | Ports and SSH | `sign_port_url`, `set_port`, `create_ssh_access`, `get_ssh` | `signPortUrl`, `setPort`, `createSshAccess`, `getSsh` |
121
+
122
+ The Python function decorator is an additional interface. This table covers the sandbox SDK, not the TypeScript agent and CI helpers.
123
+
124
+ ## Training history (internal preview)
125
+
126
+ Add `training=True` to a function to retain its observed results in Console at `/console/training`.
127
+ The organization must be internal and have the `training` feature flag.
128
+
129
+ ```python
130
+ from munitoai import App, log_metrics
131
+
132
+ app = App(region="eu")
133
+
134
+ @app.function(gpu="L4", training=True, name="French documents")
135
+ def train():
136
+ # Import dependencies here. Save checkpoints under /workspace/artifacts.
137
+ log_metrics({"loss": 0.25}, step=1)
138
+ return {"finished": True}
139
+
140
+ run = train.spawn()
141
+ print(run.training_id)
142
+ result = run.result()
143
+ run.download_artifacts("./checkpoints")
144
+ run.close()
145
+ ```
146
+
147
+ `log_metrics` uses only the Python standard library. The decorator bundles it into the guest script.
148
+ Use this exact import name outside the function. The guest does not need the SDK package.
149
+ Run history contains bounded stdout, stderr, numeric metrics, resource details, and exported-file metadata.
150
+ The preview does not upload checkpoint files or deploy models.
151
+ Each log stream retains at most 64 KiB. The record retains at most 2,048 metric reports.
152
+ The host also limits command output, so long runs can have partial logs and metrics.
153
+
154
+ `run.result()`, `run.status()`, `run.logs()`, and Console reads capture observations.
155
+ `run.close()` captures the final state before sandbox deletion.
156
+ If the client disconnects and nobody observes completion before sandbox loss, Console shows `Result unavailable`.
157
+ Use `Run.from_id(client, run_id, training_id=training_id)` to resume observation.
158
+ The sandbox timeout still bounds resource use. Console's Stop run action sends SIGTERM to the command.
159
+ Delete the sandbox to release its resources immediately.
160
+
161
+ Both `Munito.training` and `AsyncMunito.training` expose `list`, `create`, `get`, `cancel`, `artifacts`, and `delete`.
162
+ The TypeScript SDK exposes these same history methods as `munito.training`.
163
+ `create` attaches an existing sandbox command. Repeated calls return its existing record.
164
+ `delete` removes terminal history. It does not delete exported files on the SDK client.
@@ -0,0 +1,12 @@
1
+ munitoai/__init__.py,sha256=YXo3Rl_Z6ZGPzKMWrvhyD5f6leYS5Zzj_vGIGuMOcTw,609
2
+ munitoai/async_client.py,sha256=93rEgmTeY4GEjhqIgxQfiiVfBHyUb_ddWuE4w6ucFJM,9070
3
+ munitoai/client.py,sha256=7gSMi5Gd1Rpf5IV1QV80fwtVMRMlJNg8qqku1MueyGM,10873
4
+ munitoai/functions.py,sha256=LkkshCe1VC-Cd7e96Ki5fpdTNcZxX6weux72q4XYWuw,14391
5
+ munitoai/headers.py,sha256=oedgryP5RAfYsnogBukbyajfUJuN_aZEqiSmSxRfaVI,193
6
+ munitoai/models.py,sha256=HpeX4vuEPdPQOnQf9eHrfD1vZjzOOlunENaTTXIduaY,1985
7
+ munitoai/options.py,sha256=tuIdQrjbsQLYK7UYFCqsHOm4uSgPO9uLjfoV_PT57JQ,1015
8
+ munitoai/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ munitoai/training.py,sha256=OTGi8zHLxVXEPvdYZh1xJpk4R_DoYRfRwjwa2O4Br9c,3567
10
+ munitoai-0.1.0b1.dist-info/METADATA,sha256=ADtYPw5subaVmCr75AC119VWP1-ZM0yrjvv8ZnjFR9s,7536
11
+ munitoai-0.1.0b1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
12
+ munitoai-0.1.0b1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any