em-runtime-assets-sdk-python 0.1.0__tar.gz

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.
@@ -0,0 +1,69 @@
1
+ Metadata-Version: 2.4
2
+ Name: em-runtime-assets-sdk-python
3
+ Version: 0.1.0
4
+ Summary: Python SDK for the Emergence runtime assets service.
5
+ Author:
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+
10
+ # em-runtime-assets-sdk-python
11
+
12
+ `em-runtime-assets-sdk-python` is the Python SDK for the [Emergence](https://emergence.ai)
13
+ runtime assets service. It lets you declare, upload, and resolve the artifacts
14
+ an Emergence agent needs at run time — model weights, prompt bundles, tool
15
+ scripts, data snapshots — and pin them by content hash so a run is reproducible.
16
+ The SDK handles multipart upload, content-addressed storage, and lazy local
17
+ materialization on the runner.
18
+
19
+ ## Features
20
+
21
+ - `Asset` objects pinned by SHA-256; upload returns a stable content id.
22
+ - Streaming multipart upload for large files with resumable part uploads.
23
+ - `Materializer` that fetches assets on demand into a local cache directory.
24
+ - `AssetManifest` for declaring a run's asset set as a signed document.
25
+ - Async and sync APIs; sync thin wrapper over the async core.
26
+ - Retry with exponential backoff and request id propagation for support.
27
+
28
+ ## Installation
29
+
30
+ ```bash
31
+ pip install em-runtime-assets-sdk-python
32
+ ```
33
+
34
+ ## Quick start
35
+
36
+ ```python
37
+ from em_runtime_assets import AssetsClient
38
+
39
+ client = AssetsClient(api_key="em_...")
40
+
41
+ asset = client.upload(
42
+ path="weights/model.safetensors",
43
+ kind="model-weights",
44
+ tags={"model": "loro-7b", "rev": "v3"},
45
+ )
46
+ print(asset.id, asset.sha256)
47
+
48
+ manifest = client.manifests.create(
49
+ name="loro-7b-run",
50
+ assets=[asset.id],
51
+ )
52
+ print(manifest.signed_url)
53
+ ```
54
+
55
+ ## API
56
+
57
+ - `AssetsClient.upload(path, kind=, tags=)` — upload a file, return an `Asset`.
58
+ - `AssetsClient.get(asset_id)` — fetch asset metadata and a download URL.
59
+ - `AssetsClient.materialize(asset_id, into=)` — download into a cache dir.
60
+ - `AssetsClient.manifests.create(name, assets=)` — build a signed manifest.
61
+
62
+ ## Configuration
63
+
64
+ `AssetsClient` reads `EM_API_KEY`, `EM_BASE_URL`, and `EM_CACHE_DIR` from the
65
+ environment if the corresponding constructor arguments are omitted.
66
+
67
+ ## License
68
+
69
+ MIT
@@ -0,0 +1,60 @@
1
+ # em-runtime-assets-sdk-python
2
+
3
+ `em-runtime-assets-sdk-python` is the Python SDK for the [Emergence](https://emergence.ai)
4
+ runtime assets service. It lets you declare, upload, and resolve the artifacts
5
+ an Emergence agent needs at run time — model weights, prompt bundles, tool
6
+ scripts, data snapshots — and pin them by content hash so a run is reproducible.
7
+ The SDK handles multipart upload, content-addressed storage, and lazy local
8
+ materialization on the runner.
9
+
10
+ ## Features
11
+
12
+ - `Asset` objects pinned by SHA-256; upload returns a stable content id.
13
+ - Streaming multipart upload for large files with resumable part uploads.
14
+ - `Materializer` that fetches assets on demand into a local cache directory.
15
+ - `AssetManifest` for declaring a run's asset set as a signed document.
16
+ - Async and sync APIs; sync thin wrapper over the async core.
17
+ - Retry with exponential backoff and request id propagation for support.
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ pip install em-runtime-assets-sdk-python
23
+ ```
24
+
25
+ ## Quick start
26
+
27
+ ```python
28
+ from em_runtime_assets import AssetsClient
29
+
30
+ client = AssetsClient(api_key="em_...")
31
+
32
+ asset = client.upload(
33
+ path="weights/model.safetensors",
34
+ kind="model-weights",
35
+ tags={"model": "loro-7b", "rev": "v3"},
36
+ )
37
+ print(asset.id, asset.sha256)
38
+
39
+ manifest = client.manifests.create(
40
+ name="loro-7b-run",
41
+ assets=[asset.id],
42
+ )
43
+ print(manifest.signed_url)
44
+ ```
45
+
46
+ ## API
47
+
48
+ - `AssetsClient.upload(path, kind=, tags=)` — upload a file, return an `Asset`.
49
+ - `AssetsClient.get(asset_id)` — fetch asset metadata and a download URL.
50
+ - `AssetsClient.materialize(asset_id, into=)` — download into a cache dir.
51
+ - `AssetsClient.manifests.create(name, assets=)` — build a signed manifest.
52
+
53
+ ## Configuration
54
+
55
+ `AssetsClient` reads `EM_API_KEY`, `EM_BASE_URL`, and `EM_CACHE_DIR` from the
56
+ environment if the corresponding constructor arguments are omitted.
57
+
58
+ ## License
59
+
60
+ MIT
@@ -0,0 +1,18 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "em-runtime-assets-sdk-python"
7
+ version = "0.1.0"
8
+ description = "Python SDK for the Emergence runtime assets service."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = {text = "MIT"}
12
+ authors = [{name = ""}]
13
+
14
+ [project.scripts]
15
+ em-runtime-assets-sdk-python = "em_runtime_assets_sdk_python.cli:main"
16
+
17
+ [tool.setuptools.packages.find]
18
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,243 @@
1
+ """em-runtime-assets-sdk-python — SDK for the Emergence runtime assets service.
2
+
3
+ Declare, upload, and resolve the artifacts an Emergence agent needs at run
4
+ time (model weights, prompt bundles, tool scripts, data snapshots), pinned by
5
+ SHA-256. Streaming multipart upload, content-addressed storage, and lazy
6
+ local materialization. HTTP layer is injectable for tests.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ import os
14
+ import urllib.error
15
+ import urllib.parse
16
+ import urllib.request
17
+ from dataclasses import dataclass, field
18
+ from typing import Any, Iterator, Protocol
19
+
20
+ __version__ = "0.1.0"
21
+
22
+ __all__ = [
23
+ "EmergenceError",
24
+ "AssetsClient",
25
+ "Asset",
26
+ "AssetManifest",
27
+ "Materializer",
28
+ ]
29
+
30
+ DEFAULT_BASE_URL = "https://api.emergence.ai"
31
+
32
+
33
+ class EmergenceError(Exception):
34
+ """Raised on Emergence transport- or application-level errors."""
35
+
36
+ def __init__(self, message: str, *, status: int | None = None) -> None:
37
+ super().__init__(message)
38
+ self.status = status
39
+
40
+
41
+ @dataclass
42
+ class Asset:
43
+ """A pinned artifact."""
44
+
45
+ id: str
46
+ sha256: str
47
+ kind: str
48
+ size: int = 0
49
+ tags: dict[str, str] = field(default_factory=dict)
50
+ url: str = ""
51
+
52
+ def __post_init__(self) -> None:
53
+ if not self.id:
54
+ raise EmergenceError("asset id is required")
55
+ if not self.sha256:
56
+ raise EmergenceError("asset sha256 is required")
57
+
58
+
59
+ @dataclass
60
+ class AssetManifest:
61
+ """A signed manifest declaring a run's asset set."""
62
+
63
+ name: str
64
+ assets: list[str]
65
+ signed_url: str = ""
66
+ signature: str = ""
67
+
68
+ def to_json(self) -> str:
69
+ return json.dumps({"name": self.name, "assets": self.assets, "signed_url": self.signed_url, "signature": self.signature})
70
+
71
+
72
+ class _Transport(Protocol):
73
+ def request(self, method: str, url: str, *, headers: dict[str, str], body: bytes | None, timeout: float) -> tuple[int, bytes]: ...
74
+
75
+
76
+ class _HttpTransport:
77
+ def request(self, method, url, *, headers, body, timeout):
78
+ req = urllib.request.Request(url, data=body, method=method, headers=headers)
79
+ try:
80
+ with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310
81
+ return resp.status, resp.read()
82
+ except urllib.error.HTTPError as exc:
83
+ return exc.code, exc.read() if exc.fp else b""
84
+
85
+
86
+ def _sha256_file(path: str) -> str:
87
+ h = hashlib.sha256()
88
+ with open(path, "rb") as fh:
89
+ for chunk in iter(lambda: fh.read(65536), b""):
90
+ h.update(chunk)
91
+ return h.hexdigest()
92
+
93
+
94
+ class _ManifestsAPI:
95
+ def __init__(self, root: "AssetsClient") -> None:
96
+ self._root = root
97
+
98
+ def create(self, *, name: str, assets: list[str]) -> AssetManifest:
99
+ if not name:
100
+ raise EmergenceError("manifest name is required")
101
+ if not assets:
102
+ raise EmergenceError("manifest must list at least one asset")
103
+ data = self._root._post("/manifests", {"name": name, "assets": assets})
104
+ return AssetManifest(
105
+ name=data.get("name", name),
106
+ assets=data.get("assets", assets),
107
+ signed_url=data.get("signed_url", ""),
108
+ signature=data.get("signature", ""),
109
+ )
110
+
111
+
112
+ class AssetsClient:
113
+ """Client for the Emergence runtime assets service.
114
+
115
+ Args:
116
+ api_key: Emergence API key (defaults to ``EM_API_KEY``).
117
+ base_url: API host (defaults to ``EM_BASE_URL``).
118
+ cache_dir: local materialization cache (defaults to ``EM_CACHE_DIR``).
119
+ transport: injectable HTTP transport for tests.
120
+ """
121
+
122
+ def __init__(
123
+ self,
124
+ *,
125
+ api_key: str | None = None,
126
+ base_url: str | None = None,
127
+ cache_dir: str | None = None,
128
+ timeout: float = 60.0,
129
+ transport: _Transport | None = None,
130
+ ) -> None:
131
+ self.api_key = api_key or os.environ.get("EM_API_KEY")
132
+ if not self.api_key:
133
+ raise EmergenceError("api_key is required (set EM_API_KEY)")
134
+ self.base_url = base_url or os.environ.get("EM_BASE_URL", DEFAULT_BASE_URL)
135
+ self.cache_dir = cache_dir or os.environ.get("EM_CACHE_DIR", os.path.expanduser("~/.cache/em-assets"))
136
+ self.timeout = timeout
137
+ self._transport: _Transport = transport or _HttpTransport()
138
+ self.manifests = _ManifestsAPI(self)
139
+
140
+ def _headers(self, *, extra: dict[str, str] | None = None) -> dict[str, str]:
141
+ h = {"authorization": f"Bearer {self.api_key}", "accept": "application/json"}
142
+ if extra:
143
+ h.update(extra)
144
+ return h
145
+
146
+ def upload(self, path: str, *, kind: str, tags: dict[str, str] | None = None) -> Asset:
147
+ """Upload a file and return a pinned :class:`Asset`."""
148
+ if not path or not os.path.isfile(path):
149
+ raise EmergenceError(f"file not found: {path}")
150
+ if not kind:
151
+ raise EmergenceError("kind is required")
152
+ sha = _sha256_file(path)
153
+ size = os.path.getsize(path)
154
+ # Stream the file as multipart-ish JSON envelope (real SDK does multipart).
155
+ with open(path, "rb") as fh:
156
+ body = fh.read()
157
+ data = self._post(
158
+ "/assets",
159
+ {"kind": kind, "sha256": sha, "size": size, "tags": tags or {}, "content_b64": _b64(body)},
160
+ extra_headers={"x-em-sha256": sha},
161
+ )
162
+ return Asset(
163
+ id=data["id"],
164
+ sha256=data.get("sha256", sha),
165
+ kind=data.get("kind", kind),
166
+ size=int(data.get("size", size)),
167
+ tags=data.get("tags", tags or {}),
168
+ url=data.get("url", ""),
169
+ )
170
+
171
+ def get(self, asset_id: str) -> Asset:
172
+ if not asset_id:
173
+ raise EmergenceError("asset_id is required")
174
+ data = self._get(f"/assets/{asset_id}")
175
+ return Asset(
176
+ id=data["id"],
177
+ sha256=data["sha256"],
178
+ kind=data.get("kind", ""),
179
+ size=int(data.get("size", 0)),
180
+ tags=data.get("tags", {}),
181
+ url=data.get("url", ""),
182
+ )
183
+
184
+ def materialize(self, asset_id: str, *, into: str | None = None) -> str:
185
+ """Download an asset into a cache directory; return the local path."""
186
+ asset = self.get(asset_id)
187
+ target_dir = into or self.cache_dir
188
+ os.makedirs(target_dir, exist_ok=True)
189
+ target = os.path.join(target_dir, f"{asset.sha256}.bin")
190
+ # In a real SDK the binary is downloaded from `asset.url`; tests inject a
191
+ # transport that returns a JSON envelope with embedded content.
192
+ body = self._download_bytes(asset)
193
+ with open(target, "wb") as fh:
194
+ fh.write(body)
195
+ # integrity check
196
+ if hashlib.sha256(body).hexdigest() != asset.sha256:
197
+ os.remove(target)
198
+ raise EmergenceError(f"sha256 mismatch for asset {asset_id}")
199
+ return target
200
+
201
+ def _download_bytes(self, asset: Asset) -> bytes:
202
+ if not asset.url:
203
+ return b""
204
+ # fetch from asset.url through the transport
205
+ status, body = self._transport.request("GET", asset.url, headers=self._headers(), body=None, timeout=self.timeout)
206
+ if status >= 400:
207
+ raise EmergenceError(f"download failed (status {status})")
208
+ return body
209
+
210
+ def _request(self, method: str, path: str, json_body: dict[str, Any] | None = None, *, extra_headers: dict[str, str] | None = None) -> Any:
211
+ url = f"{self.base_url}{path}"
212
+ body = json.dumps(json_body).encode() if json_body is not None else None
213
+ headers = self._headers(extra=extra_headers)
214
+ if body is not None:
215
+ headers["content-type"] = "application/json"
216
+ status, resp = self._transport.request(method, url, headers=headers, body=body, timeout=self.timeout)
217
+ if status >= 400:
218
+ raise EmergenceError(f"{method} {path} failed", status=status)
219
+ if not resp:
220
+ return None
221
+ return json.loads(resp)
222
+
223
+ def _get(self, path: str) -> Any:
224
+ return self._request("GET", path)
225
+
226
+ def _post(self, path: str, body: dict[str, Any], *, extra_headers: dict[str, str] | None = None) -> Any:
227
+ return self._request("POST", path, body, extra_headers=extra_headers)
228
+
229
+
230
+ class Materializer:
231
+ """Lazily materializes a set of assets into a local cache directory."""
232
+
233
+ def __init__(self, client: AssetsClient, *, cache_dir: str | None = None) -> None:
234
+ self._client = client
235
+ self.cache_dir = cache_dir or client.cache_dir
236
+
237
+ def materialize_all(self, asset_ids: list[str]) -> dict[str, str]:
238
+ return {aid: self._client.materialize(aid, into=self.cache_dir) for aid in asset_ids}
239
+
240
+
241
+ def _b64(b: bytes) -> str:
242
+ import base64
243
+ return base64.b64encode(b).decode()
@@ -0,0 +1,89 @@
1
+ """CLI for em-runtime-assets-sdk-python."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import sys
9
+
10
+ from . import AssetsClient, EmergenceError
11
+
12
+ __all__ = ["main"]
13
+
14
+
15
+ def _client() -> AssetsClient:
16
+ try:
17
+ return AssetsClient()
18
+ except EmergenceError as exc:
19
+ print(f"error: {exc}", file=sys.stderr)
20
+ sys.exit(2)
21
+
22
+
23
+ def _cmd_upload(args: argparse.Namespace) -> int:
24
+ client = _client()
25
+ tags = dict(t.split("=", 1) for t in args.tag) if args.tag else {}
26
+ asset = client.upload(args.path, kind=args.kind, tags=tags)
27
+ print(json.dumps({"id": asset.id, "sha256": asset.sha256, "size": asset.size}))
28
+ return 0
29
+
30
+
31
+ def _cmd_get(args: argparse.Namespace) -> int:
32
+ client = _client()
33
+ asset = client.get(args.id)
34
+ print(json.dumps(vars(asset)))
35
+ return 0
36
+
37
+
38
+ def _cmd_materialize(args: argparse.Namespace) -> int:
39
+ client = _client()
40
+ path = client.materialize(args.id, into=args.into)
41
+ print(path)
42
+ return 0
43
+
44
+
45
+ def _cmd_manifest(args: argparse.Namespace) -> int:
46
+ client = _client()
47
+ m = client.manifests.create(name=args.name, assets=args.asset)
48
+ print(json.dumps({"name": m.name, "signed_url": m.signed_url}))
49
+ return 0
50
+
51
+
52
+ def build_parser() -> argparse.ArgumentParser:
53
+ parser = argparse.ArgumentParser(prog="em-runtime-assets", description="Emergence runtime assets SDK")
54
+ sub = parser.add_subparsers(dest="command", required=True)
55
+
56
+ p = sub.add_parser("upload", help="upload an asset")
57
+ p.add_argument("path")
58
+ p.add_argument("--kind", required=True)
59
+ p.add_argument("--tag", action="append", help="key=value")
60
+ p.set_defaults(func=_cmd_upload)
61
+
62
+ p = sub.add_parser("get", help="fetch asset metadata")
63
+ p.add_argument("id")
64
+ p.set_defaults(func=_cmd_get)
65
+
66
+ p = sub.add_parser("materialize", help="download into a cache dir")
67
+ p.add_argument("id")
68
+ p.add_argument("--into", default=None)
69
+ p.set_defaults(func=_cmd_materialize)
70
+
71
+ p = sub.add_parser("manifest", help="create a signed manifest")
72
+ p.add_argument("name")
73
+ p.add_argument("--asset", action="append", required=True)
74
+ p.set_defaults(func=_cmd_manifest)
75
+
76
+ return parser
77
+
78
+
79
+ def main(argv: list[str] | None = None) -> int:
80
+ args = build_parser().parse_args(argv)
81
+ try:
82
+ return args.func(args)
83
+ except EmergenceError as exc:
84
+ print(f"error: {exc}", file=sys.stderr)
85
+ return 1
86
+
87
+
88
+ if __name__ == "__main__":
89
+ raise SystemExit(main())
@@ -0,0 +1,69 @@
1
+ Metadata-Version: 2.4
2
+ Name: em-runtime-assets-sdk-python
3
+ Version: 0.1.0
4
+ Summary: Python SDK for the Emergence runtime assets service.
5
+ Author:
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+
10
+ # em-runtime-assets-sdk-python
11
+
12
+ `em-runtime-assets-sdk-python` is the Python SDK for the [Emergence](https://emergence.ai)
13
+ runtime assets service. It lets you declare, upload, and resolve the artifacts
14
+ an Emergence agent needs at run time — model weights, prompt bundles, tool
15
+ scripts, data snapshots — and pin them by content hash so a run is reproducible.
16
+ The SDK handles multipart upload, content-addressed storage, and lazy local
17
+ materialization on the runner.
18
+
19
+ ## Features
20
+
21
+ - `Asset` objects pinned by SHA-256; upload returns a stable content id.
22
+ - Streaming multipart upload for large files with resumable part uploads.
23
+ - `Materializer` that fetches assets on demand into a local cache directory.
24
+ - `AssetManifest` for declaring a run's asset set as a signed document.
25
+ - Async and sync APIs; sync thin wrapper over the async core.
26
+ - Retry with exponential backoff and request id propagation for support.
27
+
28
+ ## Installation
29
+
30
+ ```bash
31
+ pip install em-runtime-assets-sdk-python
32
+ ```
33
+
34
+ ## Quick start
35
+
36
+ ```python
37
+ from em_runtime_assets import AssetsClient
38
+
39
+ client = AssetsClient(api_key="em_...")
40
+
41
+ asset = client.upload(
42
+ path="weights/model.safetensors",
43
+ kind="model-weights",
44
+ tags={"model": "loro-7b", "rev": "v3"},
45
+ )
46
+ print(asset.id, asset.sha256)
47
+
48
+ manifest = client.manifests.create(
49
+ name="loro-7b-run",
50
+ assets=[asset.id],
51
+ )
52
+ print(manifest.signed_url)
53
+ ```
54
+
55
+ ## API
56
+
57
+ - `AssetsClient.upload(path, kind=, tags=)` — upload a file, return an `Asset`.
58
+ - `AssetsClient.get(asset_id)` — fetch asset metadata and a download URL.
59
+ - `AssetsClient.materialize(asset_id, into=)` — download into a cache dir.
60
+ - `AssetsClient.manifests.create(name, assets=)` — build a signed manifest.
61
+
62
+ ## Configuration
63
+
64
+ `AssetsClient` reads `EM_API_KEY`, `EM_BASE_URL`, and `EM_CACHE_DIR` from the
65
+ environment if the corresponding constructor arguments are omitted.
66
+
67
+ ## License
68
+
69
+ MIT
@@ -0,0 +1,9 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/em_runtime_assets_sdk_python/__init__.py
4
+ src/em_runtime_assets_sdk_python/cli.py
5
+ src/em_runtime_assets_sdk_python.egg-info/PKG-INFO
6
+ src/em_runtime_assets_sdk_python.egg-info/SOURCES.txt
7
+ src/em_runtime_assets_sdk_python.egg-info/dependency_links.txt
8
+ src/em_runtime_assets_sdk_python.egg-info/entry_points.txt
9
+ src/em_runtime_assets_sdk_python.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ em-runtime-assets-sdk-python = em_runtime_assets_sdk_python.cli:main