smartypants-network 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.
- smartypants_network-0.1.0/LICENSE +21 -0
- smartypants_network-0.1.0/PKG-INFO +48 -0
- smartypants_network-0.1.0/README.md +32 -0
- smartypants_network-0.1.0/pyproject.toml +27 -0
- smartypants_network-0.1.0/setup.cfg +4 -0
- smartypants_network-0.1.0/smartypants_network.egg-info/PKG-INFO +48 -0
- smartypants_network-0.1.0/smartypants_network.egg-info/SOURCES.txt +8 -0
- smartypants_network-0.1.0/smartypants_network.egg-info/dependency_links.txt +1 -0
- smartypants_network-0.1.0/smartypants_network.egg-info/top_level.txt +1 -0
- smartypants_network-0.1.0/smartypants_network.py +309 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Howcan (Smarty Pants)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: smartypants-network
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Smarty Pants for agents: exact open models priced per token, plus sealed Linux workspaces on idle Macs. Standard library only.
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://smartypants.network/docs/agents
|
|
7
|
+
Project-URL: Source, https://github.com/Howcanio/smarty-pants
|
|
8
|
+
Keywords: llm,openai-compatible,mcp,agents,sandbox,apple-silicon
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Requires-Python: >=3.8
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# smartypants-network (Python)
|
|
18
|
+
|
|
19
|
+
The [Smarty Pants](https://smartypants.network/docs/agents) Python kit as an installable package.
|
|
20
|
+
Python 3.8 or newer, standard library only.
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
pip install smartypants-network
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
from smartypants_network import SmartyPants
|
|
28
|
+
sp = SmartyPants() # reads SMARTYPANTS_API_KEY
|
|
29
|
+
print(sp.ask("Say hello in five words."))
|
|
30
|
+
with sp.workspace(minutes=10) as ws: # one VM, many commands (our own account first)
|
|
31
|
+
ws.put_file("data.txt", "hello")
|
|
32
|
+
print(ws.run("sh", "cat data.txt | wc -c")["stdout"])
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
The module is `smartypants_network`, not `smartypants`, because PyPI already has an unrelated
|
|
36
|
+
`smartypants` package. The one-file download at https://smartypants.network/kits/smartypants.py
|
|
37
|
+
keeps `from smartypants import SmartyPants`.
|
|
38
|
+
|
|
39
|
+
For the command line, use the `smartypants` tool from the npm package (see `packages/cli`).
|
|
40
|
+
|
|
41
|
+
Build from the repo root:
|
|
42
|
+
|
|
43
|
+
```sh
|
|
44
|
+
node packages/cli/scripts/sync-kits.mjs # copies apps/gateway/agent-kit/smartypants.py here
|
|
45
|
+
python3 -m pip wheel --no-deps -w packages/python/dist packages/python
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
MIT licence. Published by the "Publish agent packages" workflow; bump `version` in pyproject.toml first.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# smartypants-network (Python)
|
|
2
|
+
|
|
3
|
+
The [Smarty Pants](https://smartypants.network/docs/agents) Python kit as an installable package.
|
|
4
|
+
Python 3.8 or newer, standard library only.
|
|
5
|
+
|
|
6
|
+
```sh
|
|
7
|
+
pip install smartypants-network
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
```python
|
|
11
|
+
from smartypants_network import SmartyPants
|
|
12
|
+
sp = SmartyPants() # reads SMARTYPANTS_API_KEY
|
|
13
|
+
print(sp.ask("Say hello in five words."))
|
|
14
|
+
with sp.workspace(minutes=10) as ws: # one VM, many commands (our own account first)
|
|
15
|
+
ws.put_file("data.txt", "hello")
|
|
16
|
+
print(ws.run("sh", "cat data.txt | wc -c")["stdout"])
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
The module is `smartypants_network`, not `smartypants`, because PyPI already has an unrelated
|
|
20
|
+
`smartypants` package. The one-file download at https://smartypants.network/kits/smartypants.py
|
|
21
|
+
keeps `from smartypants import SmartyPants`.
|
|
22
|
+
|
|
23
|
+
For the command line, use the `smartypants` tool from the npm package (see `packages/cli`).
|
|
24
|
+
|
|
25
|
+
Build from the repo root:
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
node packages/cli/scripts/sync-kits.mjs # copies apps/gateway/agent-kit/smartypants.py here
|
|
29
|
+
python3 -m pip wheel --no-deps -w packages/python/dist packages/python
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
MIT licence. Published by the "Publish agent packages" workflow; bump `version` in pyproject.toml first.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# The Python kit (apps/gateway/agent-kit/smartypants.py) as an installable package.
|
|
2
|
+
# Build: node packages/cli/scripts/sync-kits.mjs && python3 -m pip wheel --no-deps -w dist packages/python
|
|
3
|
+
# Published by .github/workflows/publish-agent-packages.yml (Nat approved MIT and the name, 9 Nov 2026).
|
|
4
|
+
[build-system]
|
|
5
|
+
requires = ["setuptools>=61"]
|
|
6
|
+
build-backend = "setuptools.build_meta"
|
|
7
|
+
|
|
8
|
+
[project]
|
|
9
|
+
name = "smartypants-network"
|
|
10
|
+
version = "0.1.0"
|
|
11
|
+
description = "Smarty Pants for agents: exact open models priced per token, plus sealed Linux workspaces on idle Macs. Standard library only."
|
|
12
|
+
readme = "README.md"
|
|
13
|
+
requires-python = ">=3.8"
|
|
14
|
+
keywords = ["llm", "openai-compatible", "mcp", "agents", "sandbox", "apple-silicon"]
|
|
15
|
+
license = {text = "MIT"}
|
|
16
|
+
classifiers = [
|
|
17
|
+
"License :: OSI Approved :: MIT License",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Operating System :: OS Independent",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Homepage = "https://smartypants.network/docs/agents"
|
|
24
|
+
Source = "https://github.com/Howcanio/smarty-pants"
|
|
25
|
+
|
|
26
|
+
[tool.setuptools]
|
|
27
|
+
py-modules = ["smartypants_network"]
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: smartypants-network
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Smarty Pants for agents: exact open models priced per token, plus sealed Linux workspaces on idle Macs. Standard library only.
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://smartypants.network/docs/agents
|
|
7
|
+
Project-URL: Source, https://github.com/Howcanio/smarty-pants
|
|
8
|
+
Keywords: llm,openai-compatible,mcp,agents,sandbox,apple-silicon
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Requires-Python: >=3.8
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# smartypants-network (Python)
|
|
18
|
+
|
|
19
|
+
The [Smarty Pants](https://smartypants.network/docs/agents) Python kit as an installable package.
|
|
20
|
+
Python 3.8 or newer, standard library only.
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
pip install smartypants-network
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
from smartypants_network import SmartyPants
|
|
28
|
+
sp = SmartyPants() # reads SMARTYPANTS_API_KEY
|
|
29
|
+
print(sp.ask("Say hello in five words."))
|
|
30
|
+
with sp.workspace(minutes=10) as ws: # one VM, many commands (our own account first)
|
|
31
|
+
ws.put_file("data.txt", "hello")
|
|
32
|
+
print(ws.run("sh", "cat data.txt | wc -c")["stdout"])
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
The module is `smartypants_network`, not `smartypants`, because PyPI already has an unrelated
|
|
36
|
+
`smartypants` package. The one-file download at https://smartypants.network/kits/smartypants.py
|
|
37
|
+
keeps `from smartypants import SmartyPants`.
|
|
38
|
+
|
|
39
|
+
For the command line, use the `smartypants` tool from the npm package (see `packages/cli`).
|
|
40
|
+
|
|
41
|
+
Build from the repo root:
|
|
42
|
+
|
|
43
|
+
```sh
|
|
44
|
+
node packages/cli/scripts/sync-kits.mjs # copies apps/gateway/agent-kit/smartypants.py here
|
|
45
|
+
python3 -m pip wheel --no-deps -w packages/python/dist packages/python
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
MIT licence. Published by the "Publish agent packages" workflow; bump `version` in pyproject.toml first.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
smartypants_network
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
"""Smarty Pants starter kit for Python 3.8+. Standard library only, nothing to install.
|
|
2
|
+
|
|
3
|
+
Docs: https://smartypants.network/docs/agents
|
|
4
|
+
|
|
5
|
+
from smartypants import SmartyPants
|
|
6
|
+
sp = SmartyPants() # reads SMARTYPANTS_API_KEY
|
|
7
|
+
print(sp.ask("Say hello in five words."))
|
|
8
|
+
print(sp.balance())
|
|
9
|
+
print(sp.run_code("python", "print(6 * 7)")) # CPU jobs: our own account first, for now
|
|
10
|
+
with sp.workspace(minutes=10) as ws: # one VM, many commands (our own account first)
|
|
11
|
+
ws.put_file("data.txt", "hello")
|
|
12
|
+
print(ws.run("sh", "cat data.txt | wc -c")["stdout"])
|
|
13
|
+
|
|
14
|
+
Run this file directly for a quick check:
|
|
15
|
+
SMARTYPANTS_API_KEY=sp_live_... python3 smartypants.py
|
|
16
|
+
|
|
17
|
+
Already use the OpenAI SDK? Point it here instead:
|
|
18
|
+
OpenAI(base_url="https://smartypants.network/v1", api_key=os.environ["SMARTYPANTS_API_KEY"])
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
import base64
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import random
|
|
25
|
+
import string
|
|
26
|
+
import time
|
|
27
|
+
import urllib.error
|
|
28
|
+
import urllib.parse
|
|
29
|
+
import urllib.request
|
|
30
|
+
|
|
31
|
+
DEFAULT_BASE_URL = "https://smartypants.network"
|
|
32
|
+
# No fixed model: the first call picks a ready text model from the live /v1/models list.
|
|
33
|
+
# Pass model="smartypants/..." to choose one yourself.
|
|
34
|
+
DEFAULT_MODEL = None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def pick_text_model(models):
|
|
38
|
+
"""The text model to use when none is given: a ready one first, then a released (active) one."""
|
|
39
|
+
text = [m for m in (models or []) if (m.get("kind") or "text") == "text"]
|
|
40
|
+
chosen = next((m for m in text if m.get("is_ready")), None) or next((m for m in text if m.get("status") == "active"), None) or (text[0] if text else None)
|
|
41
|
+
return chosen["id"] if chosen else None
|
|
42
|
+
_DONE = {"succeeded", "failed", "timed_out", "cancelled", "expired"}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class SmartyPantsError(Exception):
|
|
46
|
+
def __init__(self, message, status=None, code=None, body=None):
|
|
47
|
+
super().__init__(message)
|
|
48
|
+
self.status = status
|
|
49
|
+
self.code = code
|
|
50
|
+
self.body = body
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class SmartyPants:
|
|
54
|
+
def __init__(self, api_key=None, base_url=None, model=DEFAULT_MODEL, timeout=120):
|
|
55
|
+
self.api_key = api_key or os.environ.get("SMARTYPANTS_API_KEY") or os.environ.get("SMARTY_PANTS_API_KEY")
|
|
56
|
+
self.base_url = (base_url or os.environ.get("SMARTYPANTS_BASE_URL") or os.environ.get("SMARTY_PANTS_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
57
|
+
self.model = model
|
|
58
|
+
self.timeout = timeout
|
|
59
|
+
self._rpc_id = 0
|
|
60
|
+
|
|
61
|
+
def request(self, method, path, body=None, auth=True, headers=None):
|
|
62
|
+
if auth and not self.api_key:
|
|
63
|
+
raise SmartyPantsError("No API key. Set SMARTYPANTS_API_KEY (create one at https://smartypants.network/api).")
|
|
64
|
+
h = {"Accept": "application/json", "User-Agent": "smartypants-python-kit/1"}
|
|
65
|
+
if body is not None:
|
|
66
|
+
h["Content-Type"] = "application/json"
|
|
67
|
+
if auth:
|
|
68
|
+
h["Authorization"] = "Bearer " + self.api_key
|
|
69
|
+
h.update(headers or {})
|
|
70
|
+
data = None if body is None else json.dumps(body).encode()
|
|
71
|
+
req = urllib.request.Request(self.base_url + path, data=data, method=method, headers=h)
|
|
72
|
+
try:
|
|
73
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
|
74
|
+
text = resp.read().decode()
|
|
75
|
+
return json.loads(text) if text else None
|
|
76
|
+
except urllib.error.HTTPError as e:
|
|
77
|
+
text = e.read().decode(errors="replace")
|
|
78
|
+
try:
|
|
79
|
+
parsed = json.loads(text)
|
|
80
|
+
except ValueError:
|
|
81
|
+
parsed = text
|
|
82
|
+
err = parsed.get("error", parsed) if isinstance(parsed, dict) else {}
|
|
83
|
+
err = err if isinstance(err, dict) else {"message": str(err)}
|
|
84
|
+
message = err.get("message") or err.get("error_description") or "HTTP %d" % e.code
|
|
85
|
+
raise SmartyPantsError("%s %s failed (%d): %s" % (method, path, e.code, message),
|
|
86
|
+
status=e.code, code=err.get("code") or err.get("type"), body=parsed) from None
|
|
87
|
+
|
|
88
|
+
def models(self):
|
|
89
|
+
"""Every model with exact id, price per token and is_ready."""
|
|
90
|
+
return self.request("GET", "/v1/models")["data"]
|
|
91
|
+
|
|
92
|
+
def chat(self, messages, **options):
|
|
93
|
+
"""OpenAI-format chat completion. Extra OpenAI fields go in **options."""
|
|
94
|
+
body = {"model": self.text_model(), "max_tokens": 512}
|
|
95
|
+
body.update(options)
|
|
96
|
+
body["messages"] = messages
|
|
97
|
+
return self.request("POST", "/v1/chat/completions", body)
|
|
98
|
+
|
|
99
|
+
def text_model(self):
|
|
100
|
+
"""The model chat() uses: the one you passed, or a ready text model from the live list (looked up once)."""
|
|
101
|
+
if not self.model:
|
|
102
|
+
self.model = pick_text_model(self.models())
|
|
103
|
+
if not self.model:
|
|
104
|
+
raise SmartyPantsError("No text model is offered right now. See https://smartypants.network/v1/models.")
|
|
105
|
+
return self.model
|
|
106
|
+
|
|
107
|
+
def ask(self, prompt, system=None, thinking=False, **options):
|
|
108
|
+
"""One prompt in, the answer text out. Thinking is off unless thinking=True."""
|
|
109
|
+
messages = ([{"role": "system", "content": system}] if system else []) + [{"role": "user", "content": prompt}]
|
|
110
|
+
options.setdefault("reasoning", {"enabled": thinking})
|
|
111
|
+
reply = self.chat(messages, **options)
|
|
112
|
+
return ((reply.get("choices") or [{}])[0].get("message") or {}).get("content") or ""
|
|
113
|
+
|
|
114
|
+
def _rpc(self, method, params=None, path="/mcp/account"):
|
|
115
|
+
self._rpc_id += 1
|
|
116
|
+
payload = {"jsonrpc": "2.0", "id": self._rpc_id, "method": method}
|
|
117
|
+
if params is not None:
|
|
118
|
+
payload["params"] = params
|
|
119
|
+
return self.request("POST", path, payload, auth=path != "/mcp",
|
|
120
|
+
headers={"Accept": "application/json, text/event-stream"})
|
|
121
|
+
|
|
122
|
+
def mcp(self, tool, arguments=None, path="/mcp/account"):
|
|
123
|
+
"""Call a tool on the MCP server. Signed-in tools live at /mcp/account; the no-sign-in ones at /mcp."""
|
|
124
|
+
rpc = self._rpc("tools/call", {"name": tool, "arguments": arguments or {}}, path)
|
|
125
|
+
if rpc.get("error"):
|
|
126
|
+
raise SmartyPantsError("MCP %s: %s" % (tool, rpc["error"].get("message")), code=rpc["error"].get("code"), body=rpc)
|
|
127
|
+
result = rpc.get("result") or {}
|
|
128
|
+
if result.get("isError"):
|
|
129
|
+
raise SmartyPantsError("MCP %s: %s" % (tool, (result.get("content") or [{}])[0].get("text", "tool error")), body=rpc)
|
|
130
|
+
if "structuredContent" in result:
|
|
131
|
+
return result["structuredContent"]
|
|
132
|
+
return json.loads((result.get("content") or [{}])[0].get("text") or "null")
|
|
133
|
+
|
|
134
|
+
def mcp_tools(self, path="/mcp/account"):
|
|
135
|
+
"""Names of the MCP tools this key can use."""
|
|
136
|
+
return [t["name"] for t in (self._rpc("tools/list", path=path).get("result") or {}).get("tools", [])]
|
|
137
|
+
|
|
138
|
+
def balance(self):
|
|
139
|
+
"""Balance in US dollars: available_usd, free_credit_usd, spent_this_month_usd."""
|
|
140
|
+
return self.mcp("get_balance")
|
|
141
|
+
|
|
142
|
+
def add_credit(self, amount_usd):
|
|
143
|
+
"""A Stripe payment page for adding credit. This charges nothing: give the link to the
|
|
144
|
+
person you work for, and only they pay it. Never handle card details. The balance
|
|
145
|
+
updates about a minute after they pay."""
|
|
146
|
+
return self.mcp("add_credit", {"amount_usd": amount_usd})
|
|
147
|
+
|
|
148
|
+
def run_code(self, language, source, timeout_seconds=20, poll_seconds=5.0, wait_seconds=120):
|
|
149
|
+
"""Run a short program in a sealed Linux VM on a Mac (no network, wiped after).
|
|
150
|
+
|
|
151
|
+
Open to our own account first; other accounts get
|
|
152
|
+
403 CPU_PILOT_ACCOUNT_REQUIRED until it opens. language is "python", "node" or "sh";
|
|
153
|
+
timeout_seconds 3 to 30. Returns a dict with id, status, exitCode, timedOut,
|
|
154
|
+
stdout, stderr, stdoutTruncated, stderrTruncated and chargeMicros.
|
|
155
|
+
"""
|
|
156
|
+
key = "kit-%d-%s" % (int(time.time()), "".join(random.choice(string.ascii_lowercase + string.digits) for _ in range(8)))
|
|
157
|
+
job = self.request("POST", "/v1/cpu/jobs", {"runtime": "code-v1", "language": language, "source": source,
|
|
158
|
+
"timeoutMs": int(timeout_seconds * 1000), "idempotencyKey": key})
|
|
159
|
+
job_id, status = job["id"], job.get("status")
|
|
160
|
+
quoted = urllib.parse.quote(job_id, safe="")
|
|
161
|
+
deadline = time.time() + wait_seconds
|
|
162
|
+
while status not in _DONE:
|
|
163
|
+
if time.time() > deadline:
|
|
164
|
+
raise SmartyPantsError("CPU job %s still %s after %d s" % (job_id, status, wait_seconds), code="WAIT_TIMEOUT")
|
|
165
|
+
time.sleep(poll_seconds)
|
|
166
|
+
status = self.request("GET", "/v1/cpu/jobs/" + quoted)["status"]
|
|
167
|
+
out = {}
|
|
168
|
+
if status in ("succeeded", "failed", "timed_out"):
|
|
169
|
+
try:
|
|
170
|
+
out = (self.request("GET", "/v1/cpu/jobs/%s/result" % quoted) or {}).get("result") or {}
|
|
171
|
+
except SmartyPantsError:
|
|
172
|
+
out = {}
|
|
173
|
+
try:
|
|
174
|
+
usage = self.request("GET", "/v1/cpu/jobs/%s/usage" % quoted)
|
|
175
|
+
except SmartyPantsError:
|
|
176
|
+
usage = None
|
|
177
|
+
rows = usage if isinstance(usage, list) else ([usage] if usage else [])
|
|
178
|
+
charges = [r["chargeMicros"] for r in rows if isinstance(r, dict) and isinstance(r.get("chargeMicros"), (int, float))]
|
|
179
|
+
return {"id": job_id, "status": status, "exitCode": out.get("exitCode"), "timedOut": out.get("timedOut", status == "timed_out"),
|
|
180
|
+
"stdout": out.get("stdout", ""), "stderr": out.get("stderr", ""),
|
|
181
|
+
"stdoutTruncated": out.get("stdoutTruncated", False), "stderrTruncated": out.get("stderrTruncated", False),
|
|
182
|
+
"chargeMicros": sum(charges) if charges else None}
|
|
183
|
+
|
|
184
|
+
def workspace(self, minutes=10, wait_seconds=120, poll_seconds=1.0, inference_budget_usd=None):
|
|
185
|
+
"""Open a workspace: one sealed VM that keeps its files across many commands until it
|
|
186
|
+
ends (at most 2 hours, 10 minutes idle, or when the Mac's owner comes back).
|
|
187
|
+
Use it in a with block so it always ends. Our own account first, for now.
|
|
188
|
+
inference_budget_usd gives it its own Smarty Pants key (ws.inference["apiKey"] and
|
|
189
|
+
ws.inference["baseUrl"]) that spends at most that much and stops working when it ends."""
|
|
190
|
+
return Workspace(self, minutes, wait_seconds, poll_seconds, inference_budget_usd)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class Workspace:
|
|
194
|
+
"""One VM session. run() and put_file()/get_file() go to the guest one at a time."""
|
|
195
|
+
|
|
196
|
+
def __init__(self, sp, minutes, wait_seconds, poll_seconds, inference_budget_usd=None):
|
|
197
|
+
self.sp, self.poll_seconds = sp, poll_seconds
|
|
198
|
+
body = {"seconds": int(minutes * 60)}
|
|
199
|
+
if inference_budget_usd is not None:
|
|
200
|
+
body["inference"] = {"budgetMicros": int(round(inference_budget_usd * 1e6))}
|
|
201
|
+
session = sp.request("POST", "/v1/cpu/sessions", body)
|
|
202
|
+
self.id = session["id"]
|
|
203
|
+
self.inference = session.get("inference")
|
|
204
|
+
self._path = "/v1/cpu/sessions/" + urllib.parse.quote(self.id, safe="")
|
|
205
|
+
deadline = time.time() + wait_seconds
|
|
206
|
+
while session["status"] == "queued":
|
|
207
|
+
if time.time() > deadline:
|
|
208
|
+
self.close()
|
|
209
|
+
raise SmartyPantsError("workspace %s still waiting for a Mac after %d s" % (self.id, wait_seconds), code="WAIT_TIMEOUT")
|
|
210
|
+
time.sleep(poll_seconds)
|
|
211
|
+
session = self.status()
|
|
212
|
+
if session["status"] != "ready":
|
|
213
|
+
raise SmartyPantsError("workspace %s ended: %s" % (self.id, session.get("reason")), code=session.get("reason"))
|
|
214
|
+
|
|
215
|
+
def __enter__(self):
|
|
216
|
+
return self
|
|
217
|
+
|
|
218
|
+
def __exit__(self, *_):
|
|
219
|
+
self.close()
|
|
220
|
+
|
|
221
|
+
def status(self):
|
|
222
|
+
return self.sp.request("GET", self._path)
|
|
223
|
+
|
|
224
|
+
def close(self):
|
|
225
|
+
"""End the workspace. Its VM, files and disk are destroyed."""
|
|
226
|
+
try:
|
|
227
|
+
return self.sp.request("DELETE", self._path)
|
|
228
|
+
except SmartyPantsError:
|
|
229
|
+
return None
|
|
230
|
+
|
|
231
|
+
def _wait(self, request_id, wait_seconds, on_output=None):
|
|
232
|
+
offsets = {"stdout": 0, "stderr": 0}
|
|
233
|
+
deadline = time.time() + wait_seconds
|
|
234
|
+
while True:
|
|
235
|
+
r = self.sp.request("GET", "%s/requests/%d?stdoutOffset=%d&stderrOffset=%d"
|
|
236
|
+
% (self._path, request_id, offsets["stdout"], offsets["stderr"]))
|
|
237
|
+
for stream in ("stdout", "stderr"):
|
|
238
|
+
part = r.get(stream)
|
|
239
|
+
if part:
|
|
240
|
+
if on_output and part["text"]:
|
|
241
|
+
on_output(stream, part["text"])
|
|
242
|
+
offsets[stream] = part["nextOffset"]
|
|
243
|
+
if r["done"]:
|
|
244
|
+
if r.get("error"):
|
|
245
|
+
raise SmartyPantsError("workspace request %d failed: %s" % (request_id, r["error"]), code=r["error"])
|
|
246
|
+
return r
|
|
247
|
+
if time.time() > deadline:
|
|
248
|
+
raise SmartyPantsError("workspace request %d still running after %d s" % (request_id, wait_seconds), code="WAIT_TIMEOUT")
|
|
249
|
+
time.sleep(self.poll_seconds)
|
|
250
|
+
|
|
251
|
+
def run(self, language, source, timeout_seconds=60, on_output=None):
|
|
252
|
+
"""Run a program ("python", "node" or "sh") in the workspace folder. on_output(stream, text)
|
|
253
|
+
gets output as it arrives. Returns exitCode, timedOut, stdout and stderr (4 KiB each)."""
|
|
254
|
+
rid = self.sp.request("POST", self._path + "/exec", {"language": language, "source": source,
|
|
255
|
+
"timeoutSeconds": int(timeout_seconds)})["requestId"]
|
|
256
|
+
out = {"stdout": "", "stderr": ""}
|
|
257
|
+
def keep(stream, text):
|
|
258
|
+
out[stream] += text
|
|
259
|
+
if on_output:
|
|
260
|
+
on_output(stream, text)
|
|
261
|
+
r = self._wait(rid, timeout_seconds + 30, keep)
|
|
262
|
+
return {"exitCode": r.get("exitCode"), "timedOut": r.get("timedOut"), **out}
|
|
263
|
+
|
|
264
|
+
PIECE = 256 * 1024 # larger files move in pieces of this size, a few at a time
|
|
265
|
+
AHEAD = 4
|
|
266
|
+
|
|
267
|
+
def put_file(self, path, content):
|
|
268
|
+
"""Write a file (text or bytes, up to 64 MiB) at a relative path in the workspace."""
|
|
269
|
+
data = content.encode("utf-8") if isinstance(content, str) else bytes(content)
|
|
270
|
+
if len(data) <= 8 * 1024:
|
|
271
|
+
rid = self.sp.request("POST", self._path + "/files",
|
|
272
|
+
{"path": path, "contentBase64": base64.b64encode(data).decode("ascii")})["requestId"]
|
|
273
|
+
self._wait(rid, 60)
|
|
274
|
+
return
|
|
275
|
+
waiting = []
|
|
276
|
+
for offset in range(0, len(data), self.PIECE):
|
|
277
|
+
piece = base64.b64encode(data[offset:offset + self.PIECE]).decode("ascii")
|
|
278
|
+
waiting.append(self.sp.request("POST", self._path + "/files",
|
|
279
|
+
{"path": path, "offset": offset, "contentBase64": piece})["requestId"])
|
|
280
|
+
if len(waiting) >= self.AHEAD:
|
|
281
|
+
self._wait(waiting.pop(0), 120)
|
|
282
|
+
for rid in waiting:
|
|
283
|
+
self._wait(rid, 120)
|
|
284
|
+
|
|
285
|
+
def get_file(self, path):
|
|
286
|
+
"""Read a file (up to 64 MiB) from the workspace, as bytes."""
|
|
287
|
+
quoted = urllib.parse.quote(path, safe="/")
|
|
288
|
+
rid = self.sp.request("GET", self._path + "/files?path=" + quoted)["requestId"]
|
|
289
|
+
try:
|
|
290
|
+
return base64.b64decode(self._wait(rid, 60).get("contentBase64", ""))
|
|
291
|
+
except SmartyPantsError as error:
|
|
292
|
+
if error.code != "TOO_LARGE":
|
|
293
|
+
raise
|
|
294
|
+
piece = lambda offset: self.sp.request("GET", "%s/files?path=%s&offset=%d" % (self._path, quoted, offset))["requestId"]
|
|
295
|
+
first = self._wait(piece(0), 120)
|
|
296
|
+
size, parts = first["size"], [base64.b64decode(first.get("contentBase64", ""))]
|
|
297
|
+
offsets = list(range(self.PIECE, size, self.PIECE))
|
|
298
|
+
waiting = []
|
|
299
|
+
while offsets or waiting:
|
|
300
|
+
while offsets and len(waiting) < self.AHEAD:
|
|
301
|
+
waiting.append(piece(offsets.pop(0)))
|
|
302
|
+
parts.append(base64.b64decode(self._wait(waiting.pop(0), 120).get("contentBase64", "")))
|
|
303
|
+
return b"".join(parts)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
if __name__ == "__main__":
|
|
307
|
+
sp = SmartyPants()
|
|
308
|
+
print("Balance:", sp.balance())
|
|
309
|
+
print("Answer:", sp.ask("Name three planets, comma separated.", max_tokens=40))
|