The hosted API #
What is new: the hosted service runs exactly the operations the offline SDK runs, per customer, behind an API key. Swap tc.Local(path) for tc.Client(url, key) and nothing else changes; another customer's records are invisible to you, down to whether they exist.
Why it matters: you can prototype offline, then move to the hosted store without rewriting anything, and the results and refusal codes are the same.
The same calls over HTTP #
This block starts the real service in-process (the same app that runs on tensorchain.io) and points the SDK at it.
import hashlib, json
from fastapi.testclient import TestClient
import tensorchain.cloud as tc
from tensorchain.service.app import create_app
from tensorchain.service.config import Settings
KEYS = {"acme": "key-for-acme-0123456789", "other": "key-for-other-0123456789"}
with open("keys.json", "w") as f:
json.dump({hashlib.sha256(k.encode()).hexdigest(): t for t, k in KEYS.items()}, f)
server = TestClient(create_app(Settings(data_dir=__import__("pathlib").Path("data"), keys_file=__import__("pathlib").Path("keys.json"), dev_key=None)))
def client(tenant):
def transport(method, path, body, query):
r = server.request(method, path, json=body, params=query, headers={"Authorization": "Bearer " + KEYS[tenant]})
return r.status_code, r.json()
return tc.Client("https://tensorchain.io", KEYS[tenant], transport=transport)
acme = client("acme")
acme.add_source("photos")
acme.license("photos", "agent:trainer", ["train"])
acme.ingest("photos", [["cat.jpg", hashlib.sha256(b"cat").hexdigest(), 3]])
with acme.training("agent:trainer", "train", ["photos"]) as run:
m = run.model("e" * 64)
print("acme's model:", acme.verify(m["model"])["status"])
assert acme.verify(m["model"])["status"] == "valid"
acme's model: valid
In production the transport is plain HTTPS; the same request with curl is curl -H "Authorization: Bearer $KEY" https://tensorchain.io/v1/provenance/models.
Another customer sees nothing #
other = client("other")
print("other's sources:", other.sources(), " models:", other.models())
try:
other.verify(m["model"])
seen = "visible"
except tc.Refused as e:
seen = "%s (%s)" % (e.code, e.status)
print("acme's model, asked by other:", seen)
assert other.sources() == [] and other.models() == []
assert seen == "not_found (404)"
other's sources: [] models: [] acme's model, asked by other: not_found (404)
Refusals are the same codes everywhere #
try:
with acme.training("agent:intern", "train", ["photos"]):
pass
except tc.Refused as e:
print("refused:", e.code, e.status)
code = e.code
assert code == "licence_required:photos"
refused: licence_required:photos 403
Every route is listed in the HTTP reference; every code in refusal codes.