modgrad-obs ingest API v1 ========================= $OBS is the server URL (e.g. http://127.0.0.1:8794). $MODGRAD_TOKEN is a bearer token. Bodies are JSON whatever the Content-Type, so plain `curl -d` works. NDJSON (one JSON object per line) is accepted wherever an array of rows is. Quick start (no account) ------------------------ The one-screen version, with this server's URL filled in: GET /llms.txt (also /docs/quickstart.txt; /docs for people; /skill.md, a Claude Code skill; /pipe.py, a stdlib streaming pipe). curl -X POST $OBS/api/v1/projects -d '{"name": "coldstart"}' -> {"project": "anon-coldstart-…", "token": "obsp_…", "board": "", "claim": "", "expires_unix": …} curl -X POST $OBS/api/v1/runs/my-run/log -H "Authorization: Bearer $MODGRAD_TOKEN" -d '{"loss": 0.52}' -> {"run": "anon-…/my-run", "created": true, "dashboard": "", "rows": 1, …} curl -X POST $OBS/api/v1/runs/my-run/finish -H "Authorization: Bearer $MODGRAD_TOKEN" a run shows "running" until it is finished (or use "finish": true / ?finish=1) Open the board URL; the graph updates live. Tokens ------ Authorization: Bearer obsp_… project token: creates and writes any run in its project. A run id without "/" is put in the project: "my-run" -> "/my-run". obsr_… run token: writes one run. Returned once, when a run is created. Anonymous project tokens expire (default 30 days, see expires_unix). Dev servers (modgrad-server --dev) also accept writes without a token. Reads need no token, except in private projects (see Accounts). Anonymous projects are listed only by their board URL. Write ----- POST /api/v1/projects New anonymous project. No auth. Body optional: {"name": "coldstart"} names it anon-coldstart-<16 hex> (1-24 of a-z 0-9 -; "_", "." and spaces become "-", upper case is lowered); without a name it is anon-<16 hex>. The random part is what keeps it unlisted. POST /api/v1/runs//log Log to run . The run is created on first write (no create call needed). Body is one of: a row {"step": 10, "loss": 0.52, "acc": "71.5%"} many rows [{"step": 10, "loss": 0.52}, {"step": 11, "loss": 0.50}] (or NDJSON) an envelope {"rows": [...], "events": ["checkpoint saved"], "config": {"lr": 3e-4}, "summary": {"best_loss": 0.4}, "finish": true | {"exit_code": 0}} Row rules: step optional; missing = one past the run's last step (0 for a new run). "_step" (W&B) is accepted too. Must be a non-negative integer. t optional seconds since run start; default = server arrival time. values numbers, or numeric strings ("3.4", "7.5%", "1e-3"); null, "nan", "inf" are stored as gaps; true/false = 1/0. Units are dropped: "7.5%" is stored as 7.5. Nested objects are flattened with "/": {"train": {"loss": 1}} -> "train/loss". {"histogram": {"edges": [...], "counts": [...]}} and {"tensor": {"shape": [...], "data": [...]}} are arrays. Other values (text) are skipped and listed under "ignored". Idempotent: re-sending a row is harmless. Rows are append-only on disk and every read merges rows by step, last write wins per (step, key). Response: {"run", "created", "dashboard", "rows", "events", "finished", "token"?, "ignored"?} Limits per body (413 when passed; the parse stops at the first): 4096 rows (array elements or NDJSON lines), 65536 values in all, 32 levels of nesting, a string as long as the body (2 MiB), about 12 MiB once parsed (many small objects cost far more than their text). The SDK sends 256 rows or fewer. A token is checked before the body is read: no token, 401, nothing parsed. POST /api/v1/runs//text Raw log text (e.g. a training script's stdout). Each line is parsed for metrics ("step 1250: loss 3.48 acc 7.5%", "iter 100 | loss=2.31 | lr 3e-4", "[epoch 2/10] train_loss: 0.45", tqdm postfixes, {'loss': 0.4} dicts). A line without a step takes the last step seen in the same body, else "next". ?events=unparsed also stores the lines without metrics as events. A body is stored in batches; a line over 8 KiB is not parsed for metrics (it counts as unparsed). ?finish=1 finishes the run after this body (the last batch of a stream). Streaming: POST new lines every few seconds (each body whole lines); a stepless line at the start of a body gets "next", so print the step on every metric line. GET /pipe.py does this, wrapping a command (records its exit code) or reading a pipe: python3 modgrad_pipe.py my-run -- python -u train.py python -u train.py 2>&1 | python3 modgrad_pipe.py my-run Printed names become keys lower-cased, spaces and "-" as "_" ("Train Loss" -> train_loss). Response: {"run", "dashboard", "lines", "rows", "unparsed", "unparsed_sample", "finished"} POST /api/v1/runs//samples Text samples (generations) for SFT/RL/eval. Creates the run like .../log. Body: one sample, an array (or NDJSON), or {"samples": [...]}: {"step": 1200, "key": "eval/gsm8k", "prompt": "...", "completion": "...", "reward": 0.73, "score": 1.0, "meta": {"temperature": 0.7}} completion required (aliases: response, output, generation, text) prompt optional (aliases: input, query); key optional (default "default") step optional; missing = the run's last history step reward, score optional numbers; other unknown keys are kept under "meta". Log the same prompts at every eval step: the dashboard diffs completions of one (key, prompt) across steps. Response: {"run", "created", "dashboard", "samples": N} POST /api/v1/runs//finish Optional body: an object merged into the run summary, e.g. {"exit_code": 0}. Until a run is finished (here, "finish" in a log envelope, ?finish=1 on .../text, the end of `modgrad run`, or EOF on the SSH door) the dashboard and the index show it as running. POST /api/v1/runs Explicit create, optional: {"name"?, "project"?, "config"?, "meta"?: {"git", "hostname", …}}. 201 {"run", "token", "dashboard", "log", "text"} for a new run, 200 for a resume. Without a name the id is run--<4 hex>. Run ids: 1 to 3 "/"-separated segments of [A-Za-z0-9_.-]. Write them plainly in the URL (/api/v1/runs/proj/run-1/log) or with "/" as %2F. Read ---- GET /api/index[?project=

] run list (same schema as the static index.json) GET /api/v1/runs//history?keys=a,b&from=&to=&stride= {"steps", "t", "columns": {key: [...]}} Keys the run does not have: 404 listing its keys when none exist, else "unknown_keys" and "keys" (all of the run's keys) in the reply. GET /api/v1/runs//config | /summary | /events GET /api/v1/runs//samples?from=&to=&key=&limit= {"samples": [...newest limit (default 5000)...], "steps": [all steps], "keys": [all keys], "n": total} Samples are read from samples.jsonl directly (outside the snapshot the metric reads use), so they may be slightly newer than other reads; a torn last line is never returned. New ones also arrive over the SSE stream. GET /api/v1/runs//manifest small server-written facts, no data parsed: {"run", "epoch", "finished", "committed": {"metrics", "arrays", "events", "samples"} (byte lengths), "keys": {"metrics": [...], "arrays": [...]}, "name", "config", "meta", "summary", "start_unix", "updated"} GET /api/v1/runs//raw/ the committed bytes of metrics | arrays | events | samples (NDJSON, the files' own lines), one range at a time: Range: bytes=a-b | a- | -n (one range). Clipped to the committed length (never a torn line) and to 8 MiB per response (206 + Content-Range; continue at end+1). A first byte at or past the committed length is 416 (Content-Range: bytes */). Without Range: 200 when the stream is at most 8 MiB, else 413. Headers: X-Obs-Committed, ETag "--" (If-None-Match -> 304; the epoch changes with visibility, claim, token revocation, delete), Cache-Control. samples is not tracked in the metric snapshot: its committed length is the file length at the request, backed off to the last newline. GET /api/v1/runs//raw//url {"url", "expires_unix"}: the same read with no credential for an hour, until the project's visibility or tokens change GET /api/runs//metrics/?max_points=N {"step": [...], "value": [...]} GET /api/v1/boards/ a saved board ({"panels": [{"query"}]}); opens as /#board= Boards ------ PUT /api/v1/boards/ store a dashboard board (JSON object, e.g. {"title", "panels": [{"query": "loss{run=~\"a|b\"}", "metric": "loss", "runs": ["a", "b"]}]}) A project token stores it as "/"; tokenless needs --dev. -> {"board": "", "url": "/#board=", "get": ""} GET /api/v1/boards/ the stored board JSON GET /api/index with a project token (Authorization header) lists that project's runs. Files (checkpoints, saved files, artifacts) ----- PUT /api/v1/runs//files/ store a file of an existing run (body = the bytes), kept at runs//files/. Same token rules as log. is relative, plain names only (no "..", no leading "/", no dot-files); at most 64 MiB per file, 1 GiB per run. -> {"run", "path", "bytes"} GET /api/v1/runs//files/ the file, as a download (application/octet-stream) W&B (the unmodified wandb SDK) ----- WANDB_BASE_URL= WANDB_API_KEY= python train.py logs to run /; WANDB_PROJECT must be the token's project (or left out). Served: POST /graphql (UpsertBucket, RunResumeStatus, CreateRunFiles, the artifact upload chain) and POST /files////file_stream (history, summary, finish). Uploads (media, wandb.save, artifact files) land in the run's files; wandb.Table and wandb.Image uploads also become a table event / an image tensor. Not served: wandb.Api() reads, sweeps, downloading artifacts (use_artifact). SSH (servers started with --ssh ) --------------------------------------- Zero install: your SSH key is your account (one anonymous project per key, made on first connect; any key type; no password). python train.py 2>&1 | ssh stream stdout into a new run (auto name); output is echoed back unchanged, metric lines (as .../text) become rows, the dashboard URL is printed first on stderr. EOF finishes the run with exit_code 0; a dropped connection leaves it unfinished. python train.py 2>&1 | ssh run the same, run / ssh token a project token (obsp_…) for this API, `modgrad init` and Python; anonymous expiry ssh runs | tail | help this key's runs, latest values, usage ssh login a one-time link (10 min) that signs a browser in with this key, or adds the key to the account the browser is signed in to Links use the server's --public-url. Accounts (sign in on the web) ----------------------------- One account holds any number of credentials: email addresses, SSH keys, zafu keys, passkeys. Sign in with any; signed in, a new one is added to the account; one that belongs to another account is refused (409 cred_taken). The session is the HttpOnly cookie mg_session (30 days, sliding). Cookie requests that change state need a same-origin browser (Sec-Fetch-Site / Origin); bearer requests are unaffected. Errors here are {"error", "code"}. Origin and prefix come from --public-url when it is given (else from the request's Host / X-Forwarded-*). On its own origin (--public-url https://app.modgrad.com) links have no prefix, the cookie is Path=/, and the passkey rpId is app.modgrad.com. Under a path (--public-url https://host/app) every link keeps the path, the cookie gets Path=/app, and the Origin checked is still https://host. The cookie is host-only (no Domain), HttpOnly, SameSite=Lax, and Secure under an https URL. Passkeys and zafu keys are bound to the host: a server moved to another host starts with none. GET /api/v1/auth/methods {email, zafu, passkey, ssh: {command} | null, account | null} POST /api/v1/auth/email {"email"} -> 202 always; mails /login#email= (15 min) POST /api/v1/auth/email/consume {"token"} -> {account: {id, created}, linked, created}; 410 token_expired POST /api/v1/auth/ssh/consume {"token"} (from `ssh login`), same reply POST /api/v1/auth/zafu/challenge -> {challenge_hex, statement, expires}; sign the bytes with ed25519 POST /api/v1/auth/zafu/verify {challenge_hex, signature, public_key} (hex) POST /api/v1/auth/passkey/register/options | register/verify | login/options | login/verify (WebAuthn) POST /api/v1/auth/logout 204 GET /api/v1/auth/whoami who a request is, for services next to this server (e.g. a metered proxy): with a bearer project token {account: , via: "token", project}; else with the session cookie {account, via: "session"}. 401 {"code"}: signed_out (neither), bad_token (unknown/expired), run_token (obsr_… is not an account credential), unowned (anonymous project; claim it first). A bearer, when sent, decides; the cookie is not a fallback. Signed in (else 401 {"code": "signed_out"}): GET /api/v1/me {account, creds, projects (each with "bytes"), sessions, tokens, usage: {bytes, limit_bytes (null = unlimited)}} PATCH /api/v1/me {"handle": "<3-32 of a-z 0-9 ->" | null}: the public profile handle; 409 name_taken DELETE /api/v1/me {"confirm": ""}: account, sessions, tokens, project data GET /api/v1/u/ public profile: {handle, since, projects: [{name, description, runs, last_unix, created}]} (public projects only; no sign-in needed) GET /api/v1/explore public boards, newest activity first (no sign-in; reads no cookie or token): ?limit= (1-50, default 24) &offset= -> {total, offset, limit, next_offset, projects: [{project, owner (handle | null), description, runs, last_unix, run (the newest), metrics (≤8 names), series: {key, step, value} (≤64 points of a loss-like metric of the newest run) | null}]}. Owned public projects with runs only (a claimed anon-… one once made public): never private, unclaimed or an SSH key's project. Cached up to 60 s. Access-Control-Allow-Origin: https://modgrad.com (this route alone) POST /api/v1/me/projects {"name", "visibility"?: "private"|"public"} -> 201; 409 name_taken; 400 bad_name name: 3-40 of a-z 0-9 '-', not anon-…, not reserved PATCH /api/v1/me/projects/ {"visibility"?, "description"?: "" | null} (at least one; a recent sign-in, as for the handle); public projects appear in Explore POST /api/v1/me/claim {"project": "anon-…", "token": "obsp_… or obsc_…"}: becomes yours, private, no longer expires POST /api/v1/claim/peek {"token": "obsc_… or obsp_…"} -> {project, claimed}: the anonymous project that token claims (no sign-in needed); 404 not_found for anything else GET /api/v1/claim/ the claim link: {project, claimed} (JSON); a browser is sent to the app's claim page (/claim#) POST /api/v1/me/tokens {"project", "label", "expires_days"?} -> {id, token} (token shown once) DELETE /api/v1/me/tokens/ POST /api/v1/me/creds/ssh {"public_key": "ssh-ed25519 AAAA… comment"}: added unconfirmed; `ssh login` from that key confirms it DELETE /api/v1/me/creds/ 409 last_cred for the only one DELETE /api/v1/me/sessions/ Private projects (the default for POST /api/v1/me/projects, and claimed ones) are read only with the owner's session or a token for the project (Authorization: Bearer obsp_…): index, history, config, summary, events, samples, metrics, arrays, streams, boards. Otherwise 401 (no session or token) or 403. Public and unowned projects read as before. MCP (for coding agents) ----------------------- Preferred: run the tools locally against this server; analysis then runs on your machine and the server only stores and selects: modgrad mcp --url $OBS --token $MODGRAD_TOKEN Servers started with --mcp also serve MCP over streamable HTTP at POST /mcp (Authorization: Bearer for writes, and for reads of a private project), for agents that cannot run a local binary. Its analysis runs on the server. Live (Server-Sent Events) ------------------------- GET /api/v1/stream[?runs=a,b | ?project=

] all public runs, some runs, or one project GET /api/v1/runs//stream one run Events (data is JSON, always with "run" and "unix" except hello): hello {"runs": [{"run", "finished", "updated_unix"}], "unix"} run {"entry": } a run appeared rows {"rows": [{"step", "t", key: value, ...}]} events {"events": [{"step", "t", "text"}]} samples {"samples": [{"step", "t", "key", "prompt", "completion", ...}], "n": total} summary {"finished", "summary"} committed {"stream", "committed", "finished"} offsets only: stream (metrics|arrays|events|samples) is now `committed` bytes long; fetch the new range from .../raw/ resync {} you fell behind: refetch Naming conventions the dashboard understands -------------------------------------------- layers// per-layer metrics (layers/0/grad_norm, layers/23/act_rms): shown as a layer x step heatmap. Nested rows work: {"layers": {"0": {"grad_norm": 1.2}}} -> layers/0/grad_norm eval// evals at checkpoints (eval/gsm8k/acc): the Evals table loss, grad_norm, lr, tokens_seen, reward, kl, entropy, response_length: the default board Transports ---------- The API is served over HTTP/1.1 on TCP and, on servers started with --h3 , also over HTTP/3 (QUIC, UDP). Those servers add Alt-Svc: h3=":"; ma=86400 to every TCP response: HTTP/3 is on that UDP port of the same hostname, with a certificate for that name. Paths, bodies, tokens, errors and SSE are the same on both. TCP is always there: curl, browsers and the Python client use it. `modgrad run` / `modgrad push` switch to HTTP/3 when an https server advertises it (or with --h3), and fall back to TCP if the UDP handshake does not finish within 1.5 s (UDP blocked); --no-h3 skips the attempt. Errors ------ Every error is JSON {"error", "example", "help", "message"}: what was wrong, a corrected request, and both as one plain-text paragraph. 400 bad body, 401 missing/unknown/expired token, 403 token does not cover this run, 409 run exists with its own token, 503/504 overloaded (retry). Reads of a private project: 401 / 403 with "code": "signed_out" / "forbidden".