Drive Hull Desk from your own code
A reading of the computed hull, not of the material. The model reads the phase diagram your browser (or your script) built; it never recomputes a number. "Stable" means a vertex of the convex hull of the entries you sent, with the energies you sent - not that a phase forms, survives or can be synthesised.
Everything the web page does is available over HTTP. Build the phase diagram with the page's own
hullkit.js (pymatgen PhaseDiagram semantics, checked against pymatgen
2026.5.4: the elemental references as the lowest energy per atom of each element, the formation
energy per atom of every entry, the lower convex hull, the stable entries, the energy above hull of
every entry and the decomposition of every unstable entry and of any composition you ask about),
send the facts, and get back a verdict (sound, caveated,
unreliable) and either a reading of every metric and of the phase diagram or a
pymatgen script that reproduces every number and runs follow-up checks. The natural loop: paste the
entries, read, script, fix the entry set, re-check. Hull Desk is derived from the agent skill
@k-dense-ai/pymatgen (k-dense-ai/scientific-agent-skills, K-Dense Inc.) and its
phase_diagram_generator.py.
Two lanes: the task field
| task | what you get | extra input |
|---|---|---|
interpret | A reading of each metric (M1..M5, in order: stable entries, lowest formation energy, unstable entries within kT of the hull, entries far above the hull, compositions with more than one entry), the computed phase diagram in words (which compounds are on the hull, how the closest unstable entries decompose, the answer for each composition you asked about), your claims judged against the facts, and what the hull cannot show. | none |
script | The fixes (rebuilding without named entries, rebuilding with one method only, adding a competing phase whose energy you still have to supply, printing a decomposition, printing equilibrium reaction energies) and one complete Python script: ENTRIES_PATH = "entries.json" read with json, one ComputedEntry per row, PhaseDiagram(entries), an EXPECTED dict of every browser value checked with math.isclose, then the fixes, all inside main(). | decision: the text of an earlier interpret run (optional) |
Both lanes return the same envelope: lane, verdict, headline, tldr, the lane body, next_steps and prescan_responses. Worked requests: interpret, script. The reply shape: output contract.
Input fields
Every field is a string.
| field | required | meaning |
|---|---|---|
task | yes | interpret or script. These are the only two lanes. |
facts | yes | A JSON-encoded string holding the browser's phase diagram - see below. The page builds it with HullKit.buildInput; an API caller normally runs the free page or reproduces it. |
title | no | A label for the analysis, up to 160 characters. |
context | no | Your notes: the calculation method and correction scheme, where the energies come from, what you want to conclude. Up to 2,500 characters. |
question | no | Answered in tldr as a bullet starting "Answer:". Up to 1,500 characters. |
decision | script only | Plain text of an earlier interpret run (the page builds it with Recon.decisionText: "Verdict: ...", the headline, one line per metric reading and phase, then the next steps). Up to 5,000 characters. |
retry_note | no | Only on a retry after a malformed reply. |
The facts string
facts is a JSON string, not an object: the browser builds the phase
diagram, serialises the result with JSON.stringify and sends that text. It holds:
settings (chemical_system, elements,
entry_count, stable_entry_count, input_format strict_json /
table / pymatgen_entries, energies_entered_per_atom,
dataset_provenance, methods, the pymatgen version,
kT_298K_eV 0.025693 and show_unstable_eV 0.2);
elemental_references (element, entry_id,
energy_eV_per_atom); entries (every stable entry, then the unstable
entries closest to the hull, up to 40, each with entry_id, formula,
energy_eV_per_atom, formation_energy_eV_per_atom,
energy_above_hull_eV_per_atom, on_hull, sometimes method,
and for an unstable entry decomposes_to, a list of entry_id,
formula and atom fraction); rows_total (all entries, sent
or not); composition_analyses (query, reduced_formula,
matching_entries, decomposition, or error);
metrics (M1.., each metric, value, sometimes
fraction, entry, formula, entries or
formulas, and basis); flags (F1.. with
severity high / medium / low, category, message and
refs); browser_verdict; expected (the exact values a
pymatgen reproduction must match: stable_entry_count,
formation_energy__<ID>, e_above_hull__<ID>) and
expected_count; and clipped (what was left out for length).
Illustrative only. The object below is what the page computes for a toy Li-O system of six made-up entries (the energies are invented for this tutorial, not real DFT values; no method is named, so F1 is raised). Some long strings are shortened with "...":
{
"settings": {
"chemical_system": "Li-O",
"elements": ["Li", "O"],
"entry_count": 6,
"stable_entry_count": 4,
"input_format": "table",
"energies_entered_per_atom": false,
"dataset_provenance": {"source": "illustrative toy numbers"},
"methods": [],
"pymatgen": "2026.5.4 / pymatgen-core 2026.7.16",
"kT_298K_eV": 0.025693,
"show_unstable_eV": 0.2
},
"elemental_references": [
{"element": "Li", "entry_id": "li", "energy_eV_per_atom": -1.907},
{"element": "O", "entry_id": "o2", "energy_eV_per_atom": -4.933}
],
"entries": [
{"entry_id": "li", "formula": "Li", "energy_eV_per_atom": -1.907,
"formation_energy_eV_per_atom": 0, "energy_above_hull_eV_per_atom": 0, "on_hull": true},
{"entry_id": "o2", "formula": "O2", "energy_eV_per_atom": -4.933,
"formation_energy_eV_per_atom": 0, "energy_above_hull_eV_per_atom": 0, "on_hull": true},
{"entry_id": "li2o", "formula": "Li2O", "energy_eV_per_atom": -4.771,
"formation_energy_eV_per_atom": -1.855333333, "energy_above_hull_eV_per_atom": 0, "on_hull": true},
{"entry_id": "li2o2", "formula": "Li2O2", "energy_eV_per_atom": -4.957,
"formation_energy_eV_per_atom": -1.537, "energy_above_hull_eV_per_atom": 0, "on_hull": true},
{"entry_id": "li2o_b", "formula": "Li2O", "energy_eV_per_atom": -4.75,
"formation_energy_eV_per_atom": -1.834333333, "energy_above_hull_eV_per_atom": 0.021,
"on_hull": false,
"decomposes_to": [{"entry_id": "li2o", "formula": "Li2O", "fraction": 1}]},
{"entry_id": "lio2", "formula": "LiO2", "energy_eV_per_atom": -4.5,
"formation_energy_eV_per_atom": -0.5756666667, "energy_above_hull_eV_per_atom": 0.449,
"on_hull": false,
"decomposes_to": [
{"entry_id": "li2o2", "formula": "Li2O2", "fraction": 0.666667},
{"entry_id": "o2", "formula": "O2", "fraction": 0.333333}
]}
],
"rows_total": 6,
"composition_analyses": [
{"query": "Li3O2", "reduced_formula": "Li3O2", "matching_entries": [],
"decomposition": [
{"entry_id": "li2o", "formula": "Li2O", "fraction": 0.6},
{"entry_id": "li2o2", "formula": "Li2O2", "fraction": 0.4}
]}
],
"metrics": [
{"id": "M1", "metric": "stable_entries", "value": 4, "fraction": 0.6667,
"basis": "entries on the computed convex hull (vertices), elemental references included, of 6 entries"},
{"id": "M2", "metric": "lowest_formation_energy", "value": -1.855333333, "entry": "li2o",
"formula": "Li2O", "basis": "eV/atom relative to the elemental references"},
{"id": "M3", "metric": "near_hull_unstable", "value": 1, "entries": ["li2o_b"],
"basis": "unstable entries within kT at 298.15 K (0.025693 eV/atom) of the hull"},
{"id": "M4", "metric": "far_above_hull", "value": 1,
"basis": "entries more than 0.2 eV/atom above the hull (the script's plotting cut-off)"},
{"id": "M5", "metric": "polymorph_compositions", "value": 1, "formulas": ["Li2O"],
"basis": "reduced formulas with more than one entry; only the lowest of each can be on the hull"}
],
"flags": [
{"id": "F1", "severity": "medium", "category": "method_not_stated",
"message": "No calculation method is stated for the dataset or any entry, so nothing shows that the energies share one functional and correction scheme.",
"refs": []},
{"id": "F2", "severity": "low", "category": "near_hull",
"message": "1 unstable entry is within kT at 298.15 K (25.7 meV/atom) of the hull. ...",
"refs": ["li2o_b"]}
],
"browser_verdict": "caveated",
"expected": {
"stable_entry_count": 4,
"formation_energy__li2o": -1.855333333,
"formation_energy__li2o2": -1.537,
"e_above_hull__li2o_b": 0.021,
"e_above_hull__lio2": 0.449
},
"expected_count": 5,
"clipped": []
}
The free browser page computes this full object for any entry set you paste: the pymatgen skill's
strict entries JSON, a table of id, formula, energy_eV rows (total energy of the
formula as written), or a list of pymatgen ComputedEntry dicts. To copy it without
writing code, open a result on the page and press Download .json: the file
carries the exact facts object under browser (the page's saved examples replay for
free, so this works before any spend). Send it back as a string: json.dumps(facts),
JSON.stringify(facts) or your language's equivalent. Keep the keys and values the
browser produced: the reply is reconciled against them, and the script lane copies
expected into its reproduction check.
Building the body
The simplest way to get a body that matches the page byte for byte is to run the page's own module
in Node. hullkit.js needs hull.js (the phase diagram) and
chem.js (formula parsing with pymatgen's rules) next to it, and all three export
themselves with module.exports. The entries can be a table
(id, formula, energy_eV), the skill's strict schema-1.0 entries JSON, or a JSON list
of pymatgen entry dicts; every element needs at least one elemental entry.
// make-body.js - build the exact body the page sends, with the page's own code.
// Save https://hull-desk.skillsafe.ai/hullkit.js, hull.js and chem.js next to this file, then:
// node make-body.js entries.csv interpret "Li-O hull" "notes" "question" "Li3O2" > body.json
// entries.csv is "id, formula, energy_eV" rows (total energy of the formula as written),
// or the skill's strict entries JSON, or a JSON list of pymatgen ComputedEntry dicts.
const fs = require("fs");
const K = require("./hullkit.js");
const [file, lane = "interpret", title = "", context = "", question = "", queries = "", decision = ""] = process.argv.slice(2);
const set = { lane, title, context, question, queries, decision, basis: "total", data: fs.readFileSync(file, "utf8") };
const X = K.analyze(set);
if (X.empty) throw new Error(X.errors.join("; ") || "no entries");
const body = K.mustBeObject(K.buildInput(X, set));
fs.writeFileSync("entries.json", K.entriesJson(X)); // the dataset the script lane reads
console.error("browser verdict:", X.hint, "| stable:", X.stable.length, "of", X.entries.length, "| flags:", X.flags.map(f => f.id + " " + f.category).join(", "));
console.error("idempotency key: hull-desk:" + body.task + ":" + K.hashInput(body) + ":a1");
process.stdout.write(JSON.stringify(body));
# Or build the body in any language from a facts object you already hold, for example the
# "browser" key of the page's "Download .json" export. facts must go in as a STRING.
import json
export = json.load(open("toy-li-o-interpret.json")) # the page's .json download
facts = export["browser"]
body = {
"task": "interpret",
"title": "Toy Li-O hull",
"context": "Illustrative toy energies, not real DFT values. ...",
"question": "Is Li2O2 on the computed hull, and what does Li3O2 decompose to?",
"facts": json.dumps(facts, separators=(",", ":")),
}
json.dump(body, open("body.json", "w"))
Base URL and the envelope
Every endpoint lives under https://api.skillsafe.ai/v1/app-api and every response uses
the same envelope, so one helper covers the whole API:
{"ok": true, "data": {"job_id": "job_...", "status": "queued"}}
{"ok": false, "error": {"code": "payment_required", "message": "..."}}
The token is minted for this app (the guest endpoint takes {"slug":"hull-desk"} in
its body), so no slug header is needed afterwards. Send it as Authorization: Bearer ….
The input object IS the request body. There is no {"input": …}
wrapper. A wrapped body is answered with an unknown field 'input' warning, and the
model never sees your text.
Error codes
| status | code | what to do |
|---|---|---|
| 400 | validation_error | A field is missing or the wrong type. Every field is a string: facts must be a JSON-encoded string, not an object. |
| 401 | unauthorized | The token is missing, malformed or expired. Get a new one from the token page. |
| 402 | payment_required | The balance is below min_credits. Call /estimate first and top up. |
| 403 | forbidden | The token is valid but not for this app, or a guest token tried a metered run. A guest cannot run; sign in for a personal token. |
| 404 | not_found | Unknown job id, or the app slug does not exist. |
| 409 | conflict | The same Idempotency-Key was replayed with a different body. Change the key or send the original input. |
| 429 | rate_limited | Too many requests. Back off and retry; do not tight-loop. |
| 5xx | internal | A server-side failure. Retry with the SAME Idempotency-Key so you are not billed twice. |
1. A tiny client
One helper that sends the token, unwraps data and raises on ok: false.
The token comes from the token page (Copy token or
Copy shell export); step 2 covers the kinds of token and minting one from code.
# Every call is the same three things: the base URL, your bearer token,
# and a JSON body. Keep the token in a shell variable.
BASE="https://api.skillsafe.ai/v1/app-api"
SLUG="hull-desk"
TOKEN="$SKILLSAFE_TOKEN" # from https://hull-desk.skillsafe.ai/tokens.html
call() { # call <path> [json-body]
if [ -n "$2" ]; then
curl -sS -X POST "$BASE/$1" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d "$2"
else
curl -sS "$BASE/$1" -H "Authorization: Bearer $TOKEN"
fi
}
import json, os, urllib.error, urllib.request
BASE = "https://api.skillsafe.ai/v1/app-api"
SLUG = "hull-desk"
TOKEN = os.environ.get("SKILLSAFE_TOKEN", "YOUR_TOKEN") # from https://hull-desk.skillsafe.ai/tokens.html
def call(path, body=None):
"""Returns the unwrapped `data`, or raises with the API error code."""
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(f"{BASE}/{path}", data=data, method="POST" if body is not None else "GET")
req.add_header("Authorization", f"Bearer {TOKEN}")
if body is not None:
req.add_header("Content-Type", "application/json")
try:
with urllib.request.urlopen(req) as r:
payload = json.load(r)
except urllib.error.HTTPError as e:
payload = json.load(e)
if not payload.get("ok"):
err = payload.get("error", {})
raise RuntimeError(f"{err.get('code')}: {err.get('message')}")
return payload["data"]
import { readFileSync } from "node:fs";
const BASE = "https://api.skillsafe.ai/v1/app-api";
const SLUG = "hull-desk";
// Paste the token from https://hull-desk.skillsafe.ai/tokens.html into a file named "token",
// or replace the fallback with it.
let TOKEN = "YOUR_TOKEN";
try { TOKEN = readFileSync("token", "utf8").trim(); } catch {}
async function call(path, body) {
const res = await fetch(`${BASE}/${path}`, {
method: body ? "POST" : "GET",
headers: {
Authorization: `Bearer ${TOKEN}`,
...(body ? { "Content-Type": "application/json" } : {}),
},
body: body ? JSON.stringify(body) : undefined,
});
const payload = await res.json();
if (!payload.ok) throw new Error(`${payload.error.code}: ${payload.error.message}`);
return payload.data;
}
package main
import (
"bufio"
"bytes"
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
const (
base = "https://api.skillsafe.ai/v1/app-api"
slug = "hull-desk"
)
var token = os.Getenv("SKILLSAFE_TOKEN") // from https://hull-desk.skillsafe.ai/tokens.html
type envelope struct {
OK bool `json:"ok"`
Data json.RawMessage `json:"data"`
Error struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
func call(path string, body any) (json.RawMessage, error) {
method := http.MethodGet
var rdr io.Reader
if body != nil {
method = http.MethodPost
b, _ := json.Marshal(body)
rdr = bytes.NewReader(b)
}
req, _ := http.NewRequest(method, base+"/"+path, rdr)
req.Header.Set("Authorization", "Bearer "+token)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
var env envelope
if err := json.NewDecoder(res.Body).Decode(&env); err != nil {
return nil, err
}
if !env.OK {
return nil, fmt.Errorf("%s: %s", env.Error.Code, env.Error.Message)
}
return env.Data, nil
}
import java.net.URI;
import java.net.http.*;
public class HullDesk {
static final String BASE = "https://api.skillsafe.ai/v1/app-api";
static final String SLUG = "hull-desk";
static final String TOKEN = System.getenv().getOrDefault("SKILLSAFE_TOKEN", "YOUR_TOKEN");
static final HttpClient HTTP = HttpClient.newHttpClient();
static String call(String path, String jsonBody) throws Exception {
HttpRequest.Builder b = HttpRequest.newBuilder(URI.create(BASE + "/" + path))
.header("Authorization", "Bearer " + TOKEN);
if (jsonBody != null) {
b.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonBody));
} else {
b.GET();
}
HttpResponse<String> res = HTTP.send(b.build(), HttpResponse.BodyHandlers.ofString());
// The envelope is always {"ok":true,"data":...} or {"ok":false,"error":...}.
return res.body();
}
}
require "json"
require "net/http"
require "uri"
BASE = "https://api.skillsafe.ai/v1/app-api"
SLUG = "hull-desk"
TOKEN = ENV.fetch("SKILLSAFE_TOKEN", "YOUR_TOKEN") # from https://hull-desk.skillsafe.ai/tokens.html
def call(path, body = nil)
uri = URI("#{BASE}/#{path}")
req = body ? Net::HTTP::Post.new(uri) : Net::HTTP::Get.new(uri)
req["Authorization"] = "Bearer #{TOKEN}"
if body
req["Content-Type"] = "application/json"
req.body = JSON.generate(body)
end
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |h| h.request(req) }
payload = JSON.parse(res.body)
raise "#{payload['error']['code']}: #{payload['error']['message']}" unless payload["ok"]
payload["data"]
end
<?php
const BASE = "https://api.skillsafe.ai/v1/app-api";
const SLUG = "hull-desk";
define("TOKEN", getenv("SKILLSAFE_TOKEN") ?: "YOUR_TOKEN"); // from /tokens.html
function call(string $path, ?array $body = null) {
$ch = curl_init(BASE . "/" . $path);
$headers = ["Authorization: Bearer " . TOKEN];
if ($body !== null) {
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$payload = json_decode(curl_exec($ch), true);
curl_close($ch);
if (empty($payload["ok"])) {
throw new RuntimeException($payload["error"]["code"] . ": " . $payload["error"]["message"]);
}
return $payload["data"];
}
using System.Net.Http.Json;
using System.Text.Json;
static class HullDesk
{
const string Base = "https://api.skillsafe.ai/v1/app-api";
const string Slug = "hull-desk";
static readonly string Token =
Environment.GetEnvironmentVariable("SKILLSAFE_TOKEN") ?? "YOUR_TOKEN";
static readonly HttpClient Http = new();
public static async Task<JsonElement> Call(string path, object? body = null)
{
var req = new HttpRequestMessage(body is null ? HttpMethod.Get : HttpMethod.Post, $"{Base}/{path}");
req.Headers.Add("Authorization", $"Bearer {Token}");
if (body is not null) req.Content = JsonContent.Create(body);
var res = await Http.SendAsync(req);
var payload = await res.Content.ReadFromJsonAsync<JsonElement>();
if (!payload.GetProperty("ok").GetBoolean())
{
var e = payload.GetProperty("error");
throw new Exception($"{e.GetProperty("code")}: {e.GetProperty("message")}");
}
return payload.GetProperty("data");
}
}
2. Get a token
The easiest route is the token page: it shows the token this browser
already holds, with Copy token and Copy shell export buttons, and
a sign-in button for a personal token. A guest token, minted with
POST /guest and {"slug":"hull-desk"}, can call /me and
/estimate; the run is metered, so /run and /run-stream need
a personal token.
# The token page is the shortest path. It shows the token this browser holds and
# hands you a ready-made shell export:
#
# https://hull-desk.skillsafe.ai/tokens.html
# export SKILLSAFE_TOKEN="..."
#
# To mint a guest token from the command line instead. A guest token is enough
# for /me and /estimate; a run needs a personal token from signing in.
curl -sS -X POST "https://api.skillsafe.ai/v1/app-api/guest" \
-H "Content-Type: application/json" -d '{"slug":"hull-desk"}'
# {"ok":true,"data":{"token":"…","subject_type":"guest"}}
# Open https://hull-desk.skillsafe.ai/tokens.html and press "Copy token",
# or mint a guest token here. A guest token can call /me and /estimate but
# cannot start a metered run.
import json, urllib.request
req = urllib.request.Request(
"https://api.skillsafe.ai/v1/app-api/guest", data=b'{"slug": "hull-desk"}', method="POST")
req.add_header("Content-Type", "application/json")
with urllib.request.urlopen(req) as r:
TOKEN = json.load(r)["data"]["token"]
// Open https://hull-desk.skillsafe.ai/tokens.html and press "Copy token",
// or mint a guest token here. A guest token can call /me and /estimate but
// cannot start a metered run.
const res = await fetch("https://api.skillsafe.ai/v1/app-api/guest", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ slug: "hull-desk" }),
});
const TOKEN = (await res.json()).data.token;
// Open https://hull-desk.skillsafe.ai/tokens.html and press "Copy token",
// or mint a guest token here. A guest token can call /me and /estimate but
// cannot start a metered run.
guestReq, _ := http.NewRequest(http.MethodPost,
"https://api.skillsafe.ai/v1/app-api/guest", bytes.NewReader([]byte(`{"slug":"hull-desk"}`)))
guestReq.Header.Set("Content-Type", "application/json")
guestRes, err := http.DefaultClient.Do(guestReq)
if err != nil {
panic(err)
}
defer guestRes.Body.Close()
var guest struct {
Data struct {
Token string `json:"token"`
} `json:"data"`
}
_ = json.NewDecoder(guestRes.Body).Decode(&guest)
fmt.Println(guest.Data.Token)
// Open https://hull-desk.skillsafe.ai/tokens.html and press "Copy token",
// or mint a guest token here. A guest token can call /me and /estimate but
// cannot start a metered run.
var http = HttpClient.newHttpClient();
var guestReq = HttpRequest.newBuilder(URI.create("https://api.skillsafe.ai/v1/app-api/guest"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{\"slug\":\"hull-desk\"}"))
.build();
HttpResponse<String> guest = http.send(guestReq, HttpResponse.BodyHandlers.ofString());
System.out.println(guest.body()); // {"ok":true,"data":{"token":"…","subject_type":"guest"}}
# Open https://hull-desk.skillsafe.ai/tokens.html and press "Copy token",
# or mint a guest token here. A guest token can call /me and /estimate but
# cannot start a metered run.
require "json"
require "net/http"
require "uri"
uri = URI("https://api.skillsafe.ai/v1/app-api/guest")
req = Net::HTTP::Post.new(uri)
req["Content-Type"] = "application/json"
req.body = JSON.generate({ slug: "hull-desk" })
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |h| h.request(req) }
TOKEN = JSON.parse(res.body)["data"]["token"]
<?php
// Open https://hull-desk.skillsafe.ai/tokens.html and press "Copy token",
// or mint a guest token here. A guest token can call /me and /estimate but
// cannot start a metered run.
$ch = curl_init("https://api.skillsafe.ai/v1/app-api/guest");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(["slug" => "hull-desk"]));
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$guest = json_decode(curl_exec($ch), true);
curl_close($ch);
echo $guest["data"]["token"];
// Open https://hull-desk.skillsafe.ai/tokens.html and press "Copy token",
// or mint a guest token here. A guest token can call /me and /estimate but
// cannot start a metered run.
using var http = new HttpClient();
var guestReq = new HttpRequestMessage(HttpMethod.Post, "https://api.skillsafe.ai/v1/app-api/guest");
guestReq.Content = new StringContent("{\"slug\":\"hull-desk\"}", Encoding.UTF8, "application/json");
var guestRes = await http.SendAsync(guestReq);
var guest = await guestRes.Content.ReadFromJsonAsync<JsonElement>();
Console.WriteLine(guest.GetProperty("data").GetProperty("token").GetString());
3. Check the session and the balance
call me
# {"ok":true,"data":{"subject_type":"user","username":"you","credits":51234}}
me = call("me")
print(me["subject_type"], me.get("credits"))
const me = await call("me");
console.log(me.subject_type, me.credits);
raw, err := call("me", nil)
if err != nil {
panic(err)
}
var me struct {
SubjectType string `json:"subject_type"`
Credits int `json:"credits"`
}
_ = json.Unmarshal(raw, &me)
fmt.Println(me.SubjectType, me.Credits)
System.out.println(call("me", null));
// {"ok":true,"data":{"subject_type":"user","username":"you","credits":51234}}
me = call("me")
puts "#{me['subject_type']} #{me['credits']}"
<?php
$me = call("me");
echo $me["subject_type"], " ", $me["credits"], PHP_EOL;
var me = await HullDesk.Call("me");
Console.WriteLine(me.GetProperty("subject_type").GetString());
4. Price the run (free)
/estimate returns the model binding and the credits a run would reserve. It creates no
job and charges nothing. Expect model_alias gpt-terra and
markup_bps 1000 (a 10% markup). hold_credits is a
reservation, not the price: it is held against your balance while the run executes
and released afterwards. min_credits is the least balance that can start a run. What
you actually pay is charged_credits, reported on the finished job and in the
done event, and it is usually far lower than the hold. The body is the input object
itself, with no {"input": …} wrapper. /estimate does not validate the
body, so check the shape yourself: an object whose every value is a string, task equal
to interpret or script,
facts non-empty, and facts a JSON string that parses to an object (this is
what the page's own guard, HullKit.mustBeObject, refuses to spend without).
# body.json is the input object itself - no {"input": ...} wrapper. Build it with
# make-body.js above, or by hand. estimate does not validate it, so check the shape first:
python3 -c 'import json;b=json.load(open("body.json"));assert isinstance(b,dict) and b.get("task") in ("interpret","script") and all(isinstance(v,str) for v in b.values()) and all(b.get(k,"").strip() for k in ("facts",)) and isinstance(json.loads(b["facts"]),dict)'
INPUT=$(cat body.json)
call estimate "$INPUT"
# {"ok":true,"data":{"model":"...","model_alias":"gpt-terra",
# "markup_bps":1000,"hold_credits":...,"min_credits":...,"sponsor_enabled":false,
# "warnings":[]}}
#
# estimate creates no job and charges nothing. hold_credits is RESERVED, not the
# price; charged_credits after the run is the actual cost, usually far lower.
INPUT = json.load(open("body.json")) # built by make-body.js above, or by hand
assert isinstance(INPUT, dict) and INPUT.get("task") in ("interpret", "script")
assert all(isinstance(v, str) for v in INPUT.values())
assert all(INPUT.get(k, "").strip() for k in ("facts",))
assert isinstance(json.loads(INPUT["facts"]), dict) # facts is a JSON STRING
est = call("estimate", INPUT)
print(est["model_alias"], est["markup_bps"], est["hold_credits"], est.get("warnings"))
me = call("me")
if me.get("credits", 0) < est["min_credits"]:
raise SystemExit("top up first: balance is below min_credits")
const INPUT = JSON.parse(readFileSync("body.json", "utf8")); // built by make-body.js above
if (!INPUT || typeof INPUT !== "object" || !["interpret", "script"].includes(INPUT.task)) throw new Error("task must be interpret or script");
for (const [k, v] of Object.entries(INPUT)) if (typeof v !== "string") throw new Error(k + " must be a string");
for (const k of ["facts"]) if (!(INPUT[k] || "").trim()) throw new Error(k + " is required");
JSON.parse(INPUT.facts); // throws unless facts is a JSON string
const est = await call("estimate", INPUT);
console.log(est.model_alias, est.markup_bps, est.hold_credits, est.warnings);
const me = await call("me");
if ((me.credits ?? 0) < est.min_credits) throw new Error("top up first");
raw, _ := os.ReadFile("body.json") // built by make-body.js above
var input map[string]string // every field is a string, facts included
if err := json.Unmarshal(raw, &input); err != nil {
panic("body.json must be an object of strings: " + err.Error())
}
if input["task"] != "interpret" && input["task"] != "script" {
panic("task must be interpret or script")
}
for _, k := range []string{"facts"} {
if strings.TrimSpace(input[k]) == "" {
panic(k + " is required")
}
}
var facts map[string]any
if err := json.Unmarshal([]byte(input["facts"]), &facts); err != nil {
panic("facts must be a JSON string holding an object")
}
est, err := call("estimate", input)
if err != nil {
panic(err)
}
fmt.Println(string(est)) // model_alias gpt-terra, markup_bps 1000, hold_credits, min_credits
String input = Files.readString(Path.of("body.json")); // built by make-body.js above
if (!input.matches("(?s)\\s*\\{.*\"task\"\\s*:\\s*\"(interpret|script)\".*\\}\\s*"))
throw new IllegalStateException("body.json must be an object with task interpret or script");
String lane = input.replaceAll("(?s).*\"task\"\\s*:\\s*\"(interpret|script)\".*", "$1");
for (String k : new String[] {"facts"})
if (!input.contains("\"" + k + "\"")) throw new IllegalStateException(k + " is required");
String est = call("estimate", input);
System.out.println(est); // model_alias gpt-terra, markup_bps 1000, hold_credits, min_credits
INPUT = JSON.parse(File.read("body.json")) # built by make-body.js above
raise "task must be interpret or script" unless %w[interpret script].include?(INPUT["task"])
INPUT.each { |k, v| raise "#{k} must be a string" unless v.is_a?(String) }
%w[facts].each { |k| raise "#{k} is required" if INPUT[k].to_s.strip.empty? }
raise "facts must hold an object" unless JSON.parse(INPUT["facts"]).is_a?(Hash)
est = call("estimate", INPUT)
puts est["model_alias"], est["markup_bps"], est["hold_credits"]
<?php
$input = json_decode(file_get_contents("body.json"), true); // built by make-body.js above
if (!is_array($input) || !in_array($input["task"] ?? "", ["interpret", "script"], true)) { throw new Exception("task must be interpret or script"); }
foreach ($input as $k => $v) { if (!is_string($v)) { throw new Exception("$k must be a string"); } }
foreach (["facts"] as $k) { if (trim($input[$k] ?? "") === "") { throw new Exception("$k is required"); } }
if (!is_array(json_decode($input["facts"], true))) { throw new Exception("facts must be a JSON string"); }
$est = call("estimate", $input);
echo $est["model_alias"], " ", $est["markup_bps"], " ", $est["hold_credits"], PHP_EOL;
var input = File.ReadAllText("body.json"); // built by make-body.js above
using var doc = JsonDocument.Parse(input);
var root = doc.RootElement;
var lane = root.GetProperty("task").GetString();
if (lane != "interpret" && lane != "script") throw new Exception("task must be interpret or script");
foreach (var p in root.EnumerateObject())
if (p.Value.ValueKind != JsonValueKind.String) throw new Exception($"{p.Name} must be a string");
JsonDocument.Parse(root.GetProperty("facts").GetString()!); // facts is a JSON string
var est = await HullDesk.Call("estimate", root);
Console.WriteLine(est); // model_alias gpt-terra, markup_bps 1000, hold_credits, min_credits
5. Run it, then poll
POST /run returns a job_id; poll GET /jobs/{id} until it is
terminal. The reply is a string at data.output.output: JSON.parse
it (step 7). Send an Idempotency-Key built from the lane, a hash of the input and the
attempt number, hull-desk:<lane>:<hash>:a<attempt> (for example
hull-desk:interpret:mt6z7s12xnl3e:a1), so a retried request returns the same job instead
of billing a second run. Use one key per distinct input: changed entries, energies, asked compositions or notes (so changed
facts) or a changed reading are a new hash, the same entries in the other lane are a new key, and replaying
an old key with a different body is a 409. The page uses
HullKit.hashInput(body) for the hash (it covers task, title,
context, facts, decision and question;
make-body.js prints the key); any stable digest of the body works from other
languages. Leave retry_note out of the hash and bump the attempt instead.
# Always send an Idempotency-Key derived from the input. A retried request with
# the same key returns the SAME job instead of billing a second run.
LANE=$(printf '%s' "$INPUT" | python3 -c 'import sys,json;print(json.load(sys.stdin)["task"])') # interpret or script
KEY="hull-desk:$LANE:$(printf '%s' "$INPUT" | shasum -a 256 | cut -c1-16):a1"
JOB=$(curl -sS -X POST "$BASE/run" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: $KEY" \
-d "$INPUT" | python3 -c 'import sys,json;print(json.load(sys.stdin)["data"]["job_id"])')
while :; do
OUT=$(call "jobs/$JOB")
STATUS=$(printf '%s' "$OUT" | python3 -c 'import sys,json;print(json.load(sys.stdin)["data"]["status"])')
[ "$STATUS" = "succeeded" ] && break
[ "$STATUS" = "failed" ] && echo "$OUT" && exit 1
sleep 2
done
# {"ok":true,"data":{"job_id":"job_...","status":"succeeded",
# "output":{"output":"{\"lane\":\"interpret\",\"verdict\":\"caveated\",\"headline\":\"...\", ...}"},
# "charged_credits":...,"truncated":false}}
printf '%s' "$OUT" | python3 -c 'import sys,json;print(json.load(sys.stdin)["data"]["output"]["output"])' > reply.json
import hashlib, time
digest = hashlib.sha256(json.dumps(INPUT, sort_keys=True).encode()).hexdigest()[:16]
key = f"hull-desk:{INPUT['task']}:{digest}:a1"
req = urllib.request.Request(f"{BASE}/run", data=json.dumps(INPUT).encode(), method="POST")
req.add_header("Authorization", f"Bearer {TOKEN}")
req.add_header("Content-Type", "application/json")
req.add_header("Idempotency-Key", key)
with urllib.request.urlopen(req) as r:
job_id = json.load(r)["data"]["job_id"]
while True:
job = call(f"jobs/{job_id}")
if job["status"] in ("succeeded", "failed"):
break
time.sleep(2)
if job["status"] == "failed":
raise RuntimeError(job.get("error"))
text = job["output"]["output"] # the reply, as a string
print("charged", job.get("charged_credits"), "truncated", job.get("truncated"))
import { createHash } from "node:crypto";
const digest = createHash("sha256").update(JSON.stringify(INPUT)).digest("hex").slice(0, 16);
const key = `hull-desk:${INPUT.task}:${digest}:a1`;
const started = await fetch(`${BASE}/run`, {
method: "POST",
headers: { Authorization: `Bearer ${TOKEN}`, "Content-Type": "application/json", "Idempotency-Key": key },
body: JSON.stringify(INPUT),
}).then((r) => r.json());
if (!started.ok) throw new Error(`${started.error.code}: ${started.error.message}`);
let job = started.data;
while (job.status !== "succeeded" && job.status !== "failed") {
await new Promise((r) => setTimeout(r, 2000));
job = await call(`jobs/${job.job_id}`);
}
if (job.status === "failed") throw new Error(JSON.stringify(job.error));
const text = job.output.output; // the reply, as a string
console.log(job.charged_credits, job.truncated);
body, _ := json.Marshal(input)
sum := sha256.Sum256(body)
key := fmt.Sprintf("hull-desk:%s:%x:a1", input["task"], sum[:8])
req, _ := http.NewRequest(http.MethodPost, base+"/run", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", key)
res, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
var started struct {
Data struct {
JobID string `json:"job_id"`
} `json:"data"`
}
_ = json.NewDecoder(res.Body).Decode(&started)
res.Body.Close()
var jobOutput string
for {
raw, err := call("jobs/"+started.Data.JobID, nil)
if err != nil {
panic(err)
}
var job struct {
Status string `json:"status"`
Output struct {
Output string `json:"output"`
} `json:"output"`
Charged int `json:"charged_credits"`
Truncated bool `json:"truncated"`
}
_ = json.Unmarshal(raw, &job)
if job.Status == "succeeded" {
jobOutput = job.Output.Output
fmt.Println(job.Charged, job.Truncated)
break
}
if job.Status == "failed" {
panic(string(raw))
}
time.Sleep(2 * time.Second)
}
String key = "hull-desk:" + lane + ":" + sha256Hex(input).substring(0, 16) + ":a1";
HttpRequest run = HttpRequest.newBuilder(URI.create(BASE + "/run"))
.header("Authorization", "Bearer " + TOKEN)
.header("Content-Type", "application/json")
.header("Idempotency-Key", key)
.POST(HttpRequest.BodyPublishers.ofString(input)).build();
String started = HTTP.send(run, HttpResponse.BodyHandlers.ofString()).body();
String jobId = started.replaceAll(".*\"job_id\":\"([^\"]+)\".*", "$1");
while (true) {
String job = call("jobs/" + jobId, null);
if (job.contains("\"status\":\"succeeded\"")) { System.out.println(job); break; }
if (job.contains("\"status\":\"failed\"")) throw new RuntimeException(job);
Thread.sleep(2000);
}
// Parse data.output.output (a string holding the reply JSON) with your JSON library.
// sha256Hex: HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(input.getBytes(UTF_8)))
require "digest"
key = "hull-desk:#{INPUT['task']}:#{Digest::SHA256.hexdigest(JSON.generate(INPUT))[0, 16]}:a1"
uri = URI("#{BASE}/run")
req = Net::HTTP::Post.new(uri)
req["Authorization"] = "Bearer #{TOKEN}"
req["Content-Type"] = "application/json"
req["Idempotency-Key"] = key
req.body = JSON.generate(INPUT)
job = JSON.parse(Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |h| h.request(req) }.body)["data"]
until %w[succeeded failed].include?(job["status"])
sleep 2
job = call("jobs/#{job['job_id']}")
end
raise job.inspect if job["status"] == "failed"
text = job["output"]["output"] # the reply, as a string
puts job["charged_credits"], job["truncated"]
<?php
$key = "hull-desk:" . $input["task"] . ":" . substr(hash("sha256", json_encode($input)), 0, 16) . ":a1";
$ch = curl_init(BASE . "/run");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($input),
CURLOPT_HTTPHEADER => ["Authorization: Bearer " . TOKEN, "Content-Type: application/json", "Idempotency-Key: " . $key],
CURLOPT_RETURNTRANSFER => true,
]);
$job = json_decode(curl_exec($ch), true)["data"];
curl_close($ch);
while (!in_array($job["status"], ["succeeded", "failed"], true)) {
sleep(2);
$job = call("jobs/" . $job["job_id"]);
}
if ($job["status"] === "failed") { throw new RuntimeException(json_encode($job)); }
$text = $job["output"]["output"]; // the reply, as a string
echo $job["charged_credits"], PHP_EOL;
using System.Security.Cryptography;
var json = input; // the body.json text from step 4
var key = $"hull-desk:{lane}:" + Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(json)))[..16].ToLower() + ":a1";
var req = new HttpRequestMessage(HttpMethod.Post, "https://api.skillsafe.ai/v1/app-api/run");
req.Headers.Add("Authorization", $"Bearer {Environment.GetEnvironmentVariable("SKILLSAFE_TOKEN") ?? "YOUR_TOKEN"}");
req.Headers.Add("Idempotency-Key", key);
req.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var started = await (await new HttpClient().SendAsync(req)).Content.ReadFromJsonAsync<JsonElement>();
var jobId = started.GetProperty("data").GetProperty("job_id").GetString();
JsonElement job;
while (true)
{
job = await HullDesk.Call($"jobs/{jobId}");
var status = job.GetProperty("status").GetString();
if (status == "succeeded") break;
if (status == "failed") throw new Exception(job.ToString());
await Task.Delay(2000);
}
var output = job.GetProperty("output").GetProperty("output").GetString()!; // the reply, as a string
6. Or stream it
POST /run-stream takes the same body and headers and answers with server-sent events:
job (the job id), delta (chunks of the reply) and done (the
status, charged_credits, truncated and, when present, the full
output). A browser page may receive only tick heartbeats and then
done, never a delta, so take the reply from done.output.output
when it is there, fall back to the concatenated deltas, and fall back again to
GET /jobs/{id}.
# Server-sent events. `delta` events carry chunks of the reply; `done` carries the
# status, charged_credits and the truncated flag. Ignore `tick` heartbeats.
curl -N -X POST "$BASE/run-stream" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: $KEY" \
-H "Accept: text/event-stream" \
-d "$INPUT"
# event: job {"job_id":"job_..."}
# event: delta {"text":"{\"lane\":\"interpret\",\"verdict\":\"caveated\",\"headline\":\"The"}
# event: done {"status":"succeeded","charged_credits":...,"truncated":false}
req = urllib.request.Request(f"{BASE}/run-stream", data=json.dumps(INPUT).encode(), method="POST")
for h, v in (("Authorization", f"Bearer {TOKEN}"), ("Content-Type", "application/json"),
("Idempotency-Key", key), ("Accept", "text/event-stream")):
req.add_header(h, v)
raw, done, event = "", {}, None
with urllib.request.urlopen(req) as stream:
for line in stream:
line = line.decode().rstrip("\n")
if line.startswith("event: "):
event = line[7:]
elif line.startswith("data: ") and event == "delta":
raw += json.loads(line[6:]).get("text", "")
elif line.startswith("data: ") and event == "done":
done = json.loads(line[6:])
text = (done.get("output") or {}).get("output") or raw
print(done.get("status"), done.get("charged_credits"), done.get("truncated"))
const res = await fetch(`${BASE}/run-stream`, {
method: "POST",
headers: { Authorization: `Bearer ${TOKEN}`, "Content-Type": "application/json", "Idempotency-Key": key, Accept: "text/event-stream" },
body: JSON.stringify(INPUT),
});
const reader = res.body.getReader();
const dec = new TextDecoder();
let buf = "", raw = "", event = null, done = null;
for (;;) {
const { value, done: end } = await reader.read();
if (end) break;
buf += dec.decode(value, { stream: true });
let i;
while ((i = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, i); buf = buf.slice(i + 1);
if (line.startsWith("event: ")) event = line.slice(7);
else if (line.startsWith("data: ") && event === "delta") raw += JSON.parse(line.slice(6)).text || "";
else if (line.startsWith("data: ") && event === "done") done = JSON.parse(line.slice(6));
}
}
const streamed = done?.output?.output || raw; // browsers may get only ticks + done
console.log(done, streamed.length);
req, _ = http.NewRequest(http.MethodPost, base+"/run-stream", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", key)
req.Header.Set("Accept", "text/event-stream")
res, err = http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer res.Body.Close()
var raw strings.Builder
event := ""
sc := bufio.NewScanner(res.Body)
sc.Buffer(make([]byte, 1<<20), 1<<20)
for sc.Scan() {
line := sc.Text()
switch {
case strings.HasPrefix(line, "event: "):
event = line[7:]
case strings.HasPrefix(line, "data: ") && event == "delta":
var d struct{ Text string `json:"text"` }
_ = json.Unmarshal([]byte(line[6:]), &d)
raw.WriteString(d.Text)
case strings.HasPrefix(line, "data: ") && event == "done":
fmt.Println("done:", line[6:])
}
}
HttpRequest stream = HttpRequest.newBuilder(URI.create(BASE + "/run-stream"))
.header("Authorization", "Bearer " + TOKEN)
.header("Content-Type", "application/json")
.header("Idempotency-Key", key)
.header("Accept", "text/event-stream")
.POST(HttpRequest.BodyPublishers.ofString(input)).build();
HTTP.send(stream, HttpResponse.BodyHandlers.ofLines()).body().forEach(line -> {
// "event: delta" lines are followed by "data: {\"text\":...}"; "event: done" by the status.
if (line.startsWith("data: ")) System.out.println(line.substring(6));
});
uri = URI("#{BASE}/run-stream")
req = Net::HTTP::Post.new(uri)
{ "Authorization" => "Bearer #{TOKEN}", "Content-Type" => "application/json",
"Idempotency-Key" => key, "Accept" => "text/event-stream" }.each { |k, v| req[k] = v }
req.body = JSON.generate(INPUT)
raw, event = +"", nil
Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |h|
h.request(req) do |res|
res.read_body do |chunk|
chunk.each_line do |line|
line = line.chomp
if line.start_with?("event: ") then event = line[7..]
elsif line.start_with?("data: ") && event == "delta" then raw << JSON.parse(line[6..])["text"].to_s
elsif line.start_with?("data: ") && event == "done" then puts line[6..]
end
end
end
end
end
<?php
$raw = ""; $event = null;
$ch = curl_init(BASE . "/run-stream");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($input),
CURLOPT_HTTPHEADER => ["Authorization: Bearer " . TOKEN, "Content-Type: application/json", "Idempotency-Key: " . $key, "Accept: text/event-stream"],
CURLOPT_WRITEFUNCTION => function ($ch, $chunk) use (&$raw, &$event) {
foreach (explode("\n", $chunk) as $line) {
if (str_starts_with($line, "event: ")) $event = substr($line, 7);
elseif (str_starts_with($line, "data: ") && $event === "delta") $raw .= json_decode(substr($line, 6), true)["text"] ?? "";
elseif (str_starts_with($line, "data: ") && $event === "done") echo substr($line, 6), PHP_EOL;
}
return strlen($chunk);
},
]);
curl_exec($ch);
curl_close($ch);
var sreq = new HttpRequestMessage(HttpMethod.Post, "https://api.skillsafe.ai/v1/app-api/run-stream");
sreq.Headers.Add("Authorization", $"Bearer {Environment.GetEnvironmentVariable("SKILLSAFE_TOKEN") ?? "YOUR_TOKEN"}");
sreq.Headers.Add("Idempotency-Key", key);
sreq.Headers.Add("Accept", "text/event-stream");
sreq.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
using var sres = await new HttpClient().SendAsync(sreq, HttpCompletionOption.ResponseHeadersRead);
using var sr = new StreamReader(await sres.Content.ReadAsStreamAsync());
var raw = new System.Text.StringBuilder(); string? ev = null, line;
while ((line = await sr.ReadLineAsync()) != null)
{
if (line.StartsWith("event: ")) ev = line[7..];
else if (line.StartsWith("data: ") && ev == "delta") raw.Append(JsonSerializer.Deserialize<JsonElement>(line[6..]).GetProperty("text").GetString());
else if (line.StartsWith("data: ") && ev == "done") Console.WriteLine(line[6..]);
}
7. Parse the reply
The reply is a JSON object serialised as a string. Parse it, then check the lane.
# The reply is a JSON string inside data.output.output. Pull it out and parse it:
printf '%s' "$JOB" | python3 -c 'import sys,json;r=json.loads(json.load(sys.stdin)["output"]["output"]);print(r["verdict"],r["headline"])'
reply = json.loads(job["output"]["output"])
assert reply["lane"] == INPUT["task"], "the model answered as another lane"
print(reply["verdict"], reply["headline"])
for m in reply.get("metrics", []): # interpret lane
print(m["id"], m["reading"])
open("hull_check.py", "w").write(reply.get("script", "")) # script lane
const reply = JSON.parse(job.output.output);
if (reply.lane !== INPUT.task) throw new Error("the model answered as another lane");
console.log(reply.verdict, reply.headline);
for (const m of reply.metrics || []) console.log(m.id, m.reading); // interpret lane
if (reply.script) require("fs").writeFileSync("hull_check.py", reply.script); // script lane
var reply struct {
Lane, Verdict, Headline, Script string
Metrics []struct{ Id, Reading string }
}
if err := json.Unmarshal([]byte(job.Output.Output), &reply); err != nil { panic(err) }
fmt.Println(reply.Verdict, reply.Headline)
// With any JSON library (Jackson shown): the reply is a string that holds a JSON object.
JsonNode reply = new ObjectMapper().readTree(outputString);
System.out.println(reply.get("verdict").asText() + " " + reply.get("headline").asText());
reply = JSON.parse(job["output"]["output"])
raise "the model answered as another lane" unless reply["lane"] == INPUT["task"]
puts [reply["verdict"], reply["headline"]].join(" ")
$reply = json_decode($job["output"]["output"], true);
if ($reply["lane"] !== $input["task"]) { throw new Exception("the model answered as another lane"); }
echo $reply["verdict"], " ", $reply["headline"], "\n";
var reply = JsonSerializer.Deserialize<JsonElement>(outputString);
Console.WriteLine($"{reply.GetProperty("verdict")} {reply.GetProperty("headline")}");
Invariants worth asserting
- The verdict is never looser than
facts.browser_verdict(unreliable < caveated < sound) unless the medium or high flags that set it were dismissed. - Every flag id appears exactly once in
prescan_responses, and no answer names a flag that was never raised. - In the interpret lane there is one reading per metric id (
M1.. in the order offacts.metrics),phasesis not empty, and every composition incomposition_analysesis mentioned. - Every number in the prose exists in
factsor your notes (after rounding to 3 significant figures; an energy in eV/atom may be written in meV/atom). Every chemical formula is an entry, a decomposition product, a composition you asked about or one in your notes. Entry ids are names, not numbers. - The prose speaks of the computed hull ("on the computed hull", "computed stable"), not of the material ("can be synthesised", "stable in reality"). Decomposition fractions are atom fractions.
- In the script lane
ENTRIES_PATHis"entries.json", entries are built withComputedEntry(Composition(..., strict=True), ...), aPhaseDiagramis built,EXPECTEDcarries every key offacts.expectedwith its value, imports come only frompymatgen.core,pymatgen.analysis.phase_diagram,pymatgen.entries.computed_entries,math,jsonandpathlib, nothing touches pickle or the network, and the work sits under a__main__guard. - The page's
recon.jschecks all of this; you can run it in Node the same way ashullkit.js. The page's entries.json (for the script) button writes the exact dataset the browser analysed, which is the file the script expects (make-body.jsabove writes it too).
The output contract
The model returns one JSON object as the job's output text. Every key of the lane's contract is present; empty sections are [].
{
"lane": "interpret" | "script",
"verdict": "sound" | "caveated" | "unreliable",
"headline": "one sentence",
"tldr": ["2-5 bullets; one starts \"Answer:\" when a question was asked"],
// interpret:
"metrics": [{"id": "M1", "reading": "..."}], // one per facts.metrics item, same order
"phases": ["1-5 strings: compounds on the hull, how the closest unstable entries decompose, each asked composition"],
"claims": [{"claim": "...", "support": "supported|partly|not_supported", "why": "..."}],
"cautions": ["1-4 strings on what the hull cannot show"],
// script:
"fixes": [{"fix": "...", "why": "...", "refs": "F1"}], // 1-6; refs "" for a plain step
"script": "import json\nimport math\n...", // one complete Python script, under 9000 characters
"assumptions": ["1-4 strings"],
"checks": ["1-4 strings"],
// both:
"next_steps": ["1-5 concrete actions"],
"prescan_responses": [{"ref": "F1", "verdict": "confirmed|dismissed", "note": "..."}]
}
The script lane's script follows a fixed order: set
ENTRIES_PATH = "entries.json" and check it is an existing local file; load it with
json.loads and build one
ComputedEntry(Composition(row["composition"], strict=True), float(row["energy_eV"]), entry_id=row["entry_id"])
per item of its "entries" list; build PhaseDiagram(entries); define
EXPECTED; compute each key with pymatgen (stable_entry_count from
len(diagram.stable_entries), formation_energy__<ID> from
diagram.get_form_energy_per_atom(entry), e_above_hull__<ID> from
diagram.get_e_above_hull(entry)); compare each with
math.isclose(got, want, rel_tol=1e-6, abs_tol=1e-6); then apply the fixes. An energy
the user did not give is a named constant set to None with an
AUTHOR_INPUT_NEEDED comment, and that fix is skipped while it is None.
Imports come only from pymatgen.core, pymatgen.analysis.phase_diagram,
pymatgen.entries.computed_entries, math, json and
pathlib.
Worked example: interpret
Illustrative numbers. The toy Li-O system from the facts section above: six
invented entries, not real DFT values. The browser puts Li, O2, Li2O and Li2O2 on the hull
(M1: 4 of 6), finds a second Li2O entry 0.021 eV/atom above the hull (within kT, F2, low) and LiO2
0.449 eV/atom above it, and raises F1 (medium) because no method is named, so its read is
caveated. The body, with facts abbreviated (send the full string from
make-body.js or the page):
{
"task": "interpret",
"title": "Toy Li-O hull",
"context": "Illustrative toy energies, not real DFT values. I want to say that Li2O and Li2O2 are the only computed-stable compounds and that LiO2 is far from the hull.",
"question": "Is Li2O2 on the computed hull, and what does Li3O2 decompose to?",
"facts": "{\"settings\":{\"chemical_system\":\"Li-O\",\"elements\":[\"Li\",\"O\"],\"entry_count\":6,\"stable_entry_count\":4,\"...\":\"more\"},\"elemental_references\":[...],\"entries\":[...],\"rows_total\":6,\"composition_analyses\":[{\"query\":\"Li3O2\",\"...\":\"...\"}],\"metrics\":[...],\"flags\":[{\"id\":\"F1\",\"severity\":\"medium\",\"category\":\"method_not_stated\",\"...\":\"...\"},{\"id\":\"F2\",\"severity\":\"low\",\"category\":\"near_hull\",\"...\":\"...\"}],\"browser_verdict\":\"caveated\",\"expected\":{\"stable_entry_count\":4,\"...\":\"4 more\"},\"expected_count\":5,\"clipped\":[]}"
}
An abbreviated reply (the job's output.output, parsed; "..." marks cuts):
{
"lane": "interpret",
"verdict": "caveated",
"headline": "On this toy entry set Li2O and Li2O2 are the only compounds on the computed hull, but no method is stated for the energies.",
"tldr": [
"4 of 6 entries are on the computed hull: Li, O2, Li2O (li2o) and Li2O2 (li2o2).",
"LiO2 (lio2) sits 0.449 eV/atom above the hull and decomposes to Li2O2 and O2.",
"Answer: yes, Li2O2 is on the computed hull; Li3O2 decomposes to 0.6 Li2O + 0.4 Li2O2 in atom fractions."
],
"metrics": [
{"id": "M1", "reading": "4 of 6 entries (0.667) are vertices of the computed hull, the two elemental references included."},
{"id": "M2", "reading": "Li2O (li2o) has the lowest formation energy, -1.86 eV/atom relative to the elemental references."},
{"id": "M3", "reading": "One unstable entry, li2o_b, lies within kT at 298.15 K of the hull (21 meV/atom)."},
{"id": "M4", "reading": "One entry, lio2, is more than 0.2 eV/atom above the hull."},
{"id": "M5", "reading": "Li2O has two entries; only the lower one, li2o, can be on the hull."}
],
"phases": [
"The computed hull runs Li - Li2O - Li2O2 - O2.",
"li2o_b is a higher-energy Li2O entry and decomposes entirely to li2o.",
"Li3O2 has no entry of its own and decomposes to 0.6 Li2O + 0.4 Li2O2 (atom fractions)."
],
"claims": [
{"claim": "Li2O and Li2O2 are the only computed-stable compounds.", "support": "supported", "why": "They are the only compounds with on_hull true."},
{"claim": "LiO2 is far from the hull.", "support": "supported", "why": "lio2 is 0.449 eV/atom above the hull, beyond the 0.2 eV/atom cut-off (M4)."}
],
"cautions": [
"The hull covers only these six entries; a missing competing phase could change it.",
"It is a 0 K energy hull with no temperature, pressure or entropy terms."
],
"next_steps": ["State the functional and correction scheme for every entry.", "..."],
"prescan_responses": [
{"ref": "F1", "verdict": "confirmed", "note": "Neither the facts nor the notes name a method."},
{"ref": "F2", "verdict": "confirmed", "note": "li2o_b is 0.021 eV/atom above the hull, inside kT."}
]
}
A reply must answer F1 and F2 once each in prescan_responses, read M1 to M5 in order,
mention Li3O2, judge both claims in context against entries, and stay at
caveated or tighter unless it dismisses F1.
Worked example: script
The same toy entries (still illustrative) with the interpret reading handed over as
decision (the page fills it with Recon.decisionText of the earlier reply;
it may be empty). No question is sent in this lane. The body, with facts and
decision abbreviated:
{
"task": "script",
"title": "Toy Li-O hull",
"context": "Illustrative toy energies, not real DFT values. I want to say that Li2O and Li2O2 are the only computed-stable compounds and that LiO2 is far from the hull.",
"decision": "Verdict: caveated.\nOn this toy entry set Li2O and Li2O2 are the only compounds on the computed hull, ...\n- M1: 4 of 6 entries ...\n...\nNext steps:\n- ...",
"facts": "{\"settings\":{\"chemical_system\":\"Li-O\",\"...\":\"more\"},\"...\":\"as in the interpret example\",\"browser_verdict\":\"caveated\",\"expected\":{\"stable_entry_count\":4,\"formation_energy__li2o\":-1.855333333,\"formation_energy__li2o2\":-1.537,\"e_above_hull__li2o_b\":0.021,\"e_above_hull__lio2\":0.449},\"expected_count\":5,\"clipped\":[]}"
}
An abbreviated reply; the script string is shown decoded below it:
{
"lane": "script",
"verdict": "caveated",
"headline": "The script rebuilds the toy Li-O hull from entries.json, checks all 5 expected values, then drops li2o_b to show it does not move the hull.",
"tldr": ["The reproduction check covers stable_entry_count, 2 formation energies and 2 energies above hull.", "..."],
"fixes": [
{"fix": "Rebuild the diagram without li2o_b and print how the other entries' energies above hull change.", "why": "It is within kT of the hull; removing it shows whether the stable set depends on it.", "refs": "F2"},
{"fix": "Print get_equilibrium_reaction_energy for each stable compound.", "why": "Shows how deep each compound sits below its neighbours.", "refs": ""}
],
"script": "import json\nimport math\nfrom pathlib import Path\n...",
"assumptions": ["entries.json is the file the page wrote for this entry set.", "The energies share one method (F1: not stated)."],
"checks": ["The reproduction prints no MISMATCH line.", "The stable set is unchanged after dropping li2o_b."],
"next_steps": ["Save the page's entries.json next to hull_check.py and run python hull_check.py.", "..."],
"prescan_responses": [
{"ref": "F1", "verdict": "confirmed", "note": "No method is named; the script cannot check compatibility."},
{"ref": "F2", "verdict": "confirmed", "note": "Answered by the first fix."}
]
}
# hull_check.py - reproduce the browser's hull from entries.json (abbreviated reply script)
import json
import math
from pathlib import Path
from pymatgen.analysis.phase_diagram import PhaseDiagram
from pymatgen.core import Composition
from pymatgen.entries.computed_entries import ComputedEntry
ENTRIES_PATH = "entries.json"
EXPECTED = {
"stable_entry_count": 4,
"formation_energy__li2o": -1.855333333,
"formation_energy__li2o2": -1.537,
"e_above_hull__li2o_b": 0.021,
"e_above_hull__lio2": 0.449,
}
def load_entries(path):
rows = json.loads(Path(path).read_text(encoding="utf-8"))["entries"]
return [
ComputedEntry(Composition(row["composition"], strict=True), float(row["energy_eV"]), entry_id=row["entry_id"])
for row in rows
]
def main():
path = Path(ENTRIES_PATH)
if not path.is_file():
raise SystemExit(f"{ENTRIES_PATH} not found: save it from the Hull Desk page first")
entries = load_entries(path)
diagram = PhaseDiagram(entries)
by_id = {e.entry_id: e for e in entries}
got = {"stable_entry_count": len(diagram.stable_entries)}
for key in EXPECTED:
if key.startswith("formation_energy__"):
got[key] = diagram.get_form_energy_per_atom(by_id[key.split("__", 1)[1]])
elif key.startswith("e_above_hull__"):
got[key] = diagram.get_e_above_hull(by_id[key.split("__", 1)[1]])
bad = [k for k, want in EXPECTED.items() if not math.isclose(got[k], want, rel_tol=1e-6, abs_tol=1e-6)]
for k in bad:
print(f"MISMATCH {k}: got {got[k]!r}, expected {EXPECTED[k]!r}")
print("reproduction:", "OK" if not bad else f"{len(bad)} mismatch(es)")
# Fix 1 (F2): rebuild without li2o_b.
reduced = PhaseDiagram([e for e in entries if e.entry_id != "li2o_b"])
print("stable without li2o_b:", sorted(e.entry_id for e in reduced.stable_entries))
# Fix 2: equilibrium reaction energy of each stable compound.
for e in diagram.stable_entries:
if len(e.composition.elements) > 1:
print(e.entry_id, diagram.get_equilibrium_reaction_energy(e))
if __name__ == "__main__":
main()
The reply's script must put all 5 keys of facts.expected into
EXPECTED with the browser's values, check each with math.isclose, and
answer F2 with a fix from the allowed list. Save the page's entries.json next to the
script and run it with python hull_check.py.
Truncation and partial results
If your balance sits between min_credits and hold_credits, the run still
executes with a smaller output cap and the job carries "truncated": true. The JSON may
then stop mid-object: close it (the page's Recon.closeJson does this) and show the
sections that arrived, saying how many of the lane's sections were recovered, rather than treating
a clipped reply as complete. A clipped script is not runnable; re-run instead.