Drive What Was That? from your own code
The one metered task, sort-sighting, is available over HTTP. It takes a sky sighting - up to 8 details (when, how long, lights, colour, motion, sound, how it ended, height), each of which may be "not sure", free notes, and the page's own fit table of 9 everyday suspects - and returns a verdict and the top 3 suspects, each explained both ways (what fits, what argues against) with a check for next time, plus a headline, a note and a closing line.
The division of labour first: the page scores and ranks the suspects and a fixed rule decides the verdict; the model explains it. After a run the page checks that the verdict follows the rule, that the suspects are its top 3 in order, that no ruled-out suspect is waved through, and that no ids leak into the prose.
Base URL and the envelope
Every endpoint lives under https://api.skillsafe.ai/v1/app-api, and every response uses one envelope:
{ "ok": true, "data": { ... } }
{ "ok": false, "error": { "code": "...", "message": "..." } }
The token is minted for this app (the guest call takes {"slug":"what-was-that"}), so no slug header is needed afterwards. Send it as Authorization: Bearer …. The run body is the input object, sent bare.
| Status | Code | Meaning |
|---|---|---|
| 400 | validation_error | The body is not a JSON object, or a required field (task, sighting, notes, fit_table) is missing. |
| 401 | unauthorized | No token, or a stale one. Mint a guest token or sign in again. |
| 402 | insufficient_credits | The balance is under min_credits. Price with /estimate first. |
| 403 | forbidden | A guest token tried to run: a sort is metered and needs a personal sign-in. |
| 404 | not_found | Unknown job id. |
| 429 | rate_limited | Back off and retry. |
| 5xx | server_error | Transient. Retry with the same Idempotency-Key so a retry never double-bills. |
The task field, the input and the verdicts
Every run sends task: sort-sighting (the one task is sort-sighting); a missing or different one is still answered as sort-sighting. The verdict rule, checked in order: the top suspect has a detail against it gives still-open; otherwise a runner-up with nothing against it that fits at most 1 detail fewer gives toss-up; otherwise a top suspect fitting 6 or more details gives solved; otherwise likely.
| Field | Required | What it holds |
|---|---|---|
task | yes | Always sort-sighting. |
sighting | yes | 8 lines, detail: answer, for example how long: 1 to 5 minutes; an unknown detail reads not sure. |
notes | yes | The person's own words (up to 400 characters), or none. Read by the run, not scored by the page. |
fit_table | yes | 9 ranked lines: S1 lantern (sky lanterns) | fits 4 of 4 known: when, lights, colour, motion | against: none | open: none. |
retry_note | no | Only on the page's single reformat retry. |
The reply is one JSON object:
{"task": "sort-sighting", "verdict": "likely", "headline": "...", "suspects": [{"id": "lantern", "fits": "...", "against": "...", "test": "..."}, ...], "note": "...", "closing": "..."}
| Field | What it holds |
|---|---|
verdict | still-open, toss-up, solved or likely, by the rule above. |
headline | The verdict in plain words with the top suspect, at most 16 words. |
suspects | Exactly 3: the S1, S2 and S3 lines in order. id copied from the line; fits at most 25 words; against at most 20 words; test (a check for next time) at most 20 words. |
note | Both directions, to the person as "you", at most 40 words. |
closing | One sentence restating the verdict, at most 20 words. |
The page then checks the reply (SkyKit.check) and lists any disagreement under "The page's check".
Worked examples - every verdict
These are the four free samples on the page: the exact input the page sends and the reply that replays for free.
A line of lights after sunset - solved
Input:
{
"task": "sort-sighting",
"sighting": "when: at dusk, within about 90 min after sunset\nhow long: 1 to 5 minutes\nlights: a line of 6 or more lights\ncolour: steady white or pale yellow\nmotion: glided steadily in a straight line\nsound: no sound\nending: faded out gradually\nheight: high overhead",
"notes": "Counted about 20 dots following each other in a row.",
"fit_table": "S1 sat-train (a string of newly launched satellites) | fits 8 of 8 known: when, how long, lights, colour, motion, sound, ending, height | against: none | open: none\nS2 lantern (sky lanterns) | fits 5 of 8 known: when, how long, lights, sound, ending | against: none | open: colour, motion, height\nS3 aircraft (an aircraft) | fits 4 of 8 known: how long, colour, motion, sound | against: none | open: when, lights, ending, height\nS4 drone (a drone) | fits 3 of 8 known: when, how long, colour | against: none | open: lights, motion, sound, ending, height\nS5 satellite (a single satellite or space station) | fits 7 of 8 known: when, how long, colour, motion, sound, ending, height | against: lights | open: none\nS6 balloon (a high-altitude balloon) | fits 5 of 8 known: when, colour, sound, ending, height | against: lights | open: how long, motion\nS7 reflection (a reflection on glass) | fits 0 of 8 known: none | against: motion | open: when, how long, lights, colour, sound, ending, height\nS8 planet (a bright planet or star) | fits 3 of 8 known: when, colour, sound | against: lights, motion | open: how long, ending, height\nS9 meteor (a meteor or fireball) | fits 3 of 8 known: colour, sound, ending | against: how long, lights | open: when, motion, height"
}
Reply:
{
"task": "sort-sighting",
"verdict": "solved",
"headline": "Solved: this matches a string of newly launched satellites passing overhead.",
"suspects": [
{
"id": "sat-train",
"fits": "Matches dusk timing, 1 to 5 minutes, 6 or more lights, steady white or pale yellow, straight glide, no sound, gradual fade, high overhead.",
"against": "Nothing described argues against it.",
"test": "Check whether the lights blink or flicker; a steady, unblinking line fits better than blinking aircraft or flickering sky lanterns."
},
{
"id": "lantern",
"fits": "Matches dusk timing, 1 to 5 minutes, a line of 6 or more lights, no sound, and a gradual fade.",
"against": "Motion is open: it neither supports nor rules out this suspect here.",
"test": "Watch if it drifts with the wind or flickers like a flame, unlike a steady straight-line glide."
},
{
"id": "aircraft",
"fits": "Matches 1 to 5 minutes duration, steady white or pale yellow colour, a straight steady glide, and no sound.",
"against": "Height is open: it neither supports nor rules out this suspect here.",
"test": "Check for blinking or colored navigation lights and any engine hum, unlike a silent steady line or flame."
}
],
"note": "You watched a steady line of lights glide quietly before fading, matching a string of newly launched satellites in every detail; your count of about 20 dots following each other also fits this answer.",
"closing": "This sighting looks solved: a string of newly launched satellites explains what you saw."
}
Orange lights drifting - likely
Input:
{
"task": "sort-sighting",
"sighting": "when: at night, well after dusk\nhow long: not sure\nlights: 2 to 5 separate lights\ncolour: orange and flickering, like a flame\nmotion: drifted slowly, as if on the wind\nsound: not sure\nending: not sure\nheight: not sure",
"notes": "Saw them from the car park; music was playing somewhere nearby.",
"fit_table": "S1 lantern (sky lanterns) | fits 4 of 4 known: when, lights, colour, motion | against: none | open: none\nS2 drone (a drone) | fits 2 of 4 known: when, lights | against: none | open: colour, motion\nS3 aircraft (an aircraft) | fits 1 of 4 known: lights | against: motion | open: when, colour\nS4 satellite (a single satellite or space station) | fits 1 of 4 known: when | against: motion | open: lights, colour\nS5 planet (a bright planet or star) | fits 1 of 4 known: when | against: motion | open: lights, colour\nS6 meteor (a meteor or fireball) | fits 1 of 4 known: when | against: motion | open: lights, colour\nS7 balloon (a high-altitude balloon) | fits 1 of 4 known: motion | against: colour | open: when, lights\nS8 reflection (a reflection on glass) | fits 0 of 4 known: none | against: motion | open: when, lights, colour\nS9 sat-train (a string of newly launched satellites) | fits 0 of 4 known: none | against: colour, motion | open: when, lights"
}
Reply:
{
"task": "sort-sighting",
"verdict": "likely",
"headline": "Likely sky lanterns drifting with the wind explain what you saw.",
"suspects": [
{
"id": "lantern",
"fits": "Matches night well after dusk, 2 to 5 separate lights, orange and flickering like a flame, and a slow wind-drift motion.",
"against": "Nothing described argues against it.",
"test": "Watch if the lights keep drifting passively with any breeze rather than hovering, darting, or holding a steady path."
},
{
"id": "drone",
"fits": "Matches night well after dusk and 2 to 5 separate lights.",
"against": "Motion is open: it neither supports nor rules out this suspect here.",
"test": "Listen for a faint buzzing motor or sudden hovering and direction changes, unlike steady flight or wind drift."
},
{
"id": "aircraft",
"fits": "Matches only the 2 to 5 separate lights described.",
"against": "The slow wind-drift motion rules this out; aircraft move under their own power, not on the wind.",
"test": "Check for a steady powered flight path, unlike wind-drift or hovering and sudden direction changes."
}
],
"note": "You watched 2 to 5 orange, flickering lights drift slowly with the wind at night, matching sky lanterns; the nearby music fits a lantern-release setting, and the unclear duration, sound, ending, and height leave gaps.",
"closing": "This sighting is likely sky lanterns drifting with the wind at night."
}
Bright light low at dusk - toss-up
Input:
{
"task": "sort-sighting",
"sighting": "when: at dusk, within about 90 min after sunset\nhow long: 5 to 30 minutes\nlights: a single light\ncolour: steady white or pale yellow\nmotion: hovered, darted, stopped and started\nsound: no sound\nending: was still there when the watcher stopped looking\nheight: low, near the horizon",
"notes": "It seemed to wobble a little when I stared at it.",
"fit_table": "S1 planet (a bright planet or star) | fits 7 of 8 known: when, how long, lights, colour, sound, ending, height | against: none | open: motion\nS2 drone (a drone) | fits 6 of 8 known: when, how long, lights, colour, motion, height | against: none | open: sound, ending\nS3 balloon (a high-altitude balloon) | fits 6 of 8 known: when, how long, lights, colour, sound, ending | against: none | open: motion, height\nS4 aircraft (an aircraft) | fits 4 of 8 known: how long, lights, colour, sound | against: none | open: when, motion, ending, height\nS5 reflection (a reflection on glass) | fits 0 of 8 known: none | against: motion | open: when, how long, lights, colour, sound, ending, height\nS6 lantern (sky lanterns) | fits 5 of 8 known: when, how long, lights, sound, height | against: motion, ending | open: colour\nS7 satellite (a single satellite or space station) | fits 4 of 8 known: when, lights, colour, sound | against: motion, ending | open: how long, height\nS8 sat-train (a string of newly launched satellites) | fits 4 of 8 known: when, how long, colour, sound | against: lights, motion, ending | open: height\nS9 meteor (a meteor or fireball) | fits 3 of 8 known: lights, colour, sound | against: how long, motion, ending | open: when, height"
}
Reply:
{
"task": "sort-sighting",
"verdict": "toss-up",
"headline": "This could be either a bright planet or star, or a drone.",
"suspects": [
{
"id": "planet",
"fits": "Matches dusk timing, 5 to 30 minutes, a single light, steady white or pale yellow, no sound, still there at the end, and low height.",
"against": "Motion is open: it neither supports nor rules out this suspect here.",
"test": "Watch closely; a planet stays fixed against the background, unlike a hovering, darting drone or a drifting balloon."
},
{
"id": "drone",
"fits": "Matches dusk timing, 5 to 30 minutes, a single light, steady white or pale yellow, the hovering and darting motion, and low height.",
"against": "Sound is open: it neither supports nor rules out this suspect here.",
"test": "Listen for a faint motor hum and watch for sudden stops or darts, unlike a steady planet or slow balloon."
},
{
"id": "balloon",
"fits": "Matches dusk timing, 5 to 30 minutes, a single light, steady white or pale yellow, no sound, and still there at the end.",
"against": "Motion is open: it neither supports nor rules out this suspect here.",
"test": "Watch if it drifts slowly with any breeze rather than darting abruptly or staying perfectly fixed in place."
}
],
"note": "You watched a steady light low near the horizon, hovering and darting for 5 to 30 minutes, still there when you stopped looking; the wobble you noticed fits a twinkling planet or star, but the motion also fits a drone.",
"closing": "It's a close call between a bright planet or star and a drone, with evidence split between them."
}
A shape that hung there - still open
Input:
{
"task": "sort-sighting",
"sighting": "when: at night, well after dusk\nhow long: over 30 minutes\nlights: lights held in a fixed shape\ncolour: steady white or pale yellow\nmotion: hung still or barely moved\nsound: no sound\nending: blinked out suddenly\nheight: high overhead",
"notes": "none",
"fit_table": "S1 planet (a bright planet or star) | fits 5 of 8 known: when, how long, colour, motion, sound | against: lights | open: ending, height\nS2 balloon (a high-altitude balloon) | fits 5 of 8 known: how long, colour, motion, sound, height | against: lights | open: when, ending\nS3 drone (a drone) | fits 4 of 8 known: when, lights, colour, ending | against: how long | open: motion, sound, height\nS4 aircraft (an aircraft) | fits 2 of 8 known: colour, sound | against: how long | open: when, lights, motion, ending, height\nS5 reflection (a reflection on glass) | fits 1 of 8 known: ending | against: motion | open: when, how long, lights, colour, sound, height\nS6 lantern (sky lanterns) | fits 3 of 8 known: when, sound, ending | against: how long, lights | open: colour, motion, height\nS7 satellite (a single satellite or space station) | fits 4 of 8 known: when, colour, sound, height | against: how long, lights, motion | open: ending\nS8 meteor (a meteor or fireball) | fits 4 of 8 known: when, colour, sound, ending | against: how long, lights, motion | open: height\nS9 sat-train (a string of newly launched satellites) | fits 3 of 8 known: colour, sound, height | against: how long, lights, motion | open: when, ending"
}
Reply:
{
"task": "sort-sighting",
"verdict": "still-open",
"headline": "No everyday suspect fits every detail; a bright planet or star fits best.",
"suspects": [
{
"id": "planet",
"fits": "Matches night well after dusk, over 30 minutes, steady white or pale yellow, hanging still or barely moving, and no sound.",
"against": "The lights held in a fixed shape rule this out; a bright planet or star is a single point.",
"test": "Look closely for whether it is a single point of light or several lights arranged in a shape."
},
{
"id": "balloon",
"fits": "Matches over 30 minutes, steady white or pale yellow, hanging still or barely moving, no sound, and high overhead.",
"against": "The lights held in a fixed shape rule this out; a high-altitude balloon typically shows as a single light.",
"test": "Note whether its position slowly drifts over time, unlike a fixed star-like point or a shaped light cluster."
},
{
"id": "drone",
"fits": "Matches night well after dusk, lights held in a fixed shape, steady white or pale yellow, and a sudden blink-out ending.",
"against": "The over 30 minute duration rules this out; drones typically can't fly that long.",
"test": "Watch for the light shape shifting or moving, and listen for a motor hum, unlike a fixed point or balloon."
}
],
"note": "You watched lights held in a fixed shape high overhead for over 30 minutes before they blinked out suddenly; that fixed shape is what rules out a bright planet or star, which would show as a single point of light.",
"closing": "No everyday suspect fits every detail you described, so this sighting remains unexplained for now."
}
Build the input yourself
Load the engine in node (global.window = global; require("./skykit.js")), then:
const K = SkyKit;
const built = K.buildInput(K.form({ when: "night", duration: "minutes", lights: "one", colour: "white",
motion: "straight", sound: "none", ending: "fade", height: "high", notes: "" }));
built.input.fit_table; // the page's 9 ranked suspect lines
const wire = K.toWire(built.input); // POST this to /estimate and /run
// then: const reply = K.normalize(K.parseReply(job.output.output));
// built.facts.verdict // the verdict the page's rule gives
// K.check(reply, built).notes // the page's re-check of the reply
// K.md(built, reply, "my sighting") // the sighting as Markdown
Step 1 — a tiny client helper
One function that sends JSON and unwraps the envelope. Paste a personal token from /tokens.html, or leave it empty and mint a guest token in step 2.
BASE="https://api.skillsafe.ai/v1/app-api"
TOKEN="paste-your-token-here" # from https://what-was-that.skillsafe.ai/tokens.html
api() { # api METHOD PATH [JSON-BODY]
curl -s -X "$1" "$BASE$2" -H "Content-Type: application/json" \
${TOKEN:+-H "Authorization: Bearer $TOKEN"} ${3:+--data "$3"}
}
import json, urllib.request
BASE = "https://api.skillsafe.ai/v1/app-api"
TOKEN = "paste-your-token-here" # from https://what-was-that.skillsafe.ai/tokens.html
def api(method, path, body=None, headers=None):
req = urllib.request.Request(BASE + path, method=method,
data=None if body is None else json.dumps(body).encode(),
headers={"Content-Type": "application/json", **({"Authorization": "Bearer " + TOKEN} if TOKEN else {}), **(headers or {})})
with urllib.request.urlopen(req) as r:
env = json.load(r)
if env.get("error"):
raise RuntimeError(env["error"])
return env["data"]
// what-was-that.mjs -- Node 18+ (global fetch)
const BASE = "https://api.skillsafe.ai/v1/app-api";
let TOKEN = "paste-your-token-here"; // from https://what-was-that.skillsafe.ai/tokens.html
async function api(method, path, body, headers = {}) {
const r = await fetch(BASE + path, { method, headers: { "Content-Type": "application/json",
...(TOKEN ? { Authorization: "Bearer " + TOKEN } : {}), ...headers },
body: body === undefined ? undefined : JSON.stringify(body) });
const env = await r.json();
if (env.error) throw new Error(env.error.code + ": " + env.error.message);
return env.data;
}
package main
import ("bytes"; "encoding/json"; "fmt"; "net/http")
const base = "https://api.skillsafe.ai/v1/app-api"
var token = "paste-your-token-here" // from https://what-was-that.skillsafe.ai/tokens.html
func api(method, path string, body any, headers map[string]string) (map[string]any, error) {
var buf bytes.Buffer
if body != nil { json.NewEncoder(&buf).Encode(body) }
req, _ := http.NewRequest(method, base+path, &buf)
req.Header.Set("Content-Type", "application/json")
if token != "" { req.Header.Set("Authorization", "Bearer "+token) }
for k, v := range headers { req.Header.Set(k, v) }
res, err := http.DefaultClient.Do(req)
if err != nil { return nil, err }
defer res.Body.Close()
var env struct { Data map[string]any; Error map[string]any }
json.NewDecoder(res.Body).Decode(&env)
if env.Error != nil { return nil, fmt.Errorf("%v", env.Error) }
return env.Data, nil
}
// WhatWasThat.java -- Java 17+, with com.fasterxml.jackson.core:jackson-databind
import com.fasterxml.jackson.databind.*;
import java.net.URI; import java.net.http.*; import java.util.*;
public class WhatWasThat {
static final String BASE = "https://api.skillsafe.ai/v1/app-api";
static String token = "paste-your-token-here"; // from https://what-was-that.skillsafe.ai/tokens.html
static final ObjectMapper M = new ObjectMapper();
static final HttpClient C = HttpClient.newHttpClient();
static JsonNode api(String method, String path, Object body, Map<String, String> headers) throws Exception {
var b = HttpRequest.newBuilder(URI.create(BASE + path)).header("Content-Type", "application/json");
if (!token.isEmpty()) b.header("Authorization", "Bearer " + token);
if (headers != null) headers.forEach(b::header);
b.method(method, body == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(M.writeValueAsString(body)));
JsonNode env = M.readTree(C.send(b.build(), HttpResponse.BodyHandlers.ofString()).body());
if (env.hasNonNull("error")) throw new RuntimeException(env.get("error").toString());
return env.get("data");
}
}
require "json"
require "net/http"
BASE = "https://api.skillsafe.ai/v1/app-api"
TOKEN = "paste-your-token-here" # from https://what-was-that.skillsafe.ai/tokens.html
def api(method, path, body = nil, headers = {})
uri = URI(BASE + path)
req = Net::HTTPGenericRequest.new(method, !body.nil?, true, uri.request_uri,
{ "Content-Type" => "application/json" }.merge(TOKEN.empty? ? {} : { "Authorization" => "Bearer #{TOKEN}" }).merge(headers))
req.body = JSON.generate(body) unless body.nil?
env = JSON.parse(Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |h| h.request(req) }.body)
raise env["error"].to_s if env["error"]
env["data"]
end
<?php
const BASE = "https://api.skillsafe.ai/v1/app-api";
$TOKEN = "paste-your-token-here"; // from https://what-was-that.skillsafe.ai/tokens.html
function api(string $method, string $path, $body = null, array $headers = []) {
global $TOKEN;
$h = ["Content-Type: application/json"];
if ($TOKEN) $h[] = "Authorization: Bearer $TOKEN";
foreach ($headers as $k => $v) $h[] = "$k: $v";
$ch = curl_init(BASE . $path);
curl_setopt_array($ch, [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $h, CURLOPT_RETURNTRANSFER => true]);
if ($body !== null) curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
$env = json_decode(curl_exec($ch), true);
if (!empty($env["error"])) throw new Exception(json_encode($env["error"]));
return $env["data"];
}
// Program.cs -- .NET 6+ console app
using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Nodes;
static class Api {
public const string Base = "https://api.skillsafe.ai/v1/app-api";
public static string Token = "paste-your-token-here"; // from https://what-was-that.skillsafe.ai/tokens.html
static readonly HttpClient C = new();
public static async Task<JsonNode?> Call(string method, string path, object? body = null, Dictionary<string, string>? headers = null) {
var req = new HttpRequestMessage(new HttpMethod(method), Base + path);
if (Token != "") req.Headers.Add("Authorization", "Bearer " + Token);
if (headers != null) foreach (var h in headers) req.Headers.Add(h.Key, h.Value);
if (body != null) req.Content = JsonContent.Create(body);
var env = JsonNode.Parse(await (await C.SendAsync(req)).Content.ReadAsStringAsync())!;
if (env["error"] is JsonNode e && e.GetValueKind() != JsonValueKind.Null) throw new Exception(e.ToJsonString());
return env["data"];
}
}
Step 2 — a token
A guest token is enough for /me and /estimate. A run is metered, so it needs a personal token: sign in on /tokens.html and copy it from there.
# a guest token (enough for /me and /estimate); a run needs your personal token from /tokens.html
TOKEN=$(curl -s -X POST "$BASE/guest" -H "Content-Type: application/json" -d '{"slug":"what-was-that"}' | jq -r '.data.token')
# a guest token (enough for /me and /estimate); a run needs your personal token from /tokens.html
TOKEN = ""
TOKEN = api("POST", "/guest", {"slug": "what-was-that"})["token"]
// a guest token (enough for /me and /estimate); a run needs your personal token from /tokens.html
TOKEN = "";
TOKEN = (await api("POST", "/guest", { slug: "what-was-that" })).token;
// inside main: a guest token (enough for /me and /estimate); a run needs your personal token
token = ""
g, err := api("POST", "/guest", map[string]string{"slug": "what-was-that"}, nil)
if err != nil { panic(err) }
token = g["token"].(string)
// inside main: a guest token (enough for /me and /estimate); a run needs your personal token
token = "";
token = api("POST", "/guest", Map.of("slug", "what-was-that"), null).get("token").asText();
# a guest token (enough for /me and /estimate); a run needs your personal token from /tokens.html
TOKEN.replace("")
TOKEN.replace(api("POST", "/guest", { slug: "what-was-that" })["token"])
// a guest token (enough for /me and /estimate); a run needs your personal token from /tokens.html
$TOKEN = "";
$TOKEN = api("POST", "/guest", ["slug" => "what-was-that"])["token"];
// a guest token (enough for /me and /estimate); a run needs your personal token from /tokens.html
Api.Token = "";
Api.Token = (await Api.Call("POST", "/guest", new { slug = "what-was-that" }))!["token"]!.GetValue<string>();
Step 3 — GET /me
Who the token is (subject_type: user or guest) and the credit balance.
api GET /me | jq '.data | {subject_type, credits}'
me = api("GET", "/me")
print(me["subject_type"], me.get("credits"))
const me = await api("GET", "/me");
console.log(me.subject_type, me.credits);
me, _ := api("GET", "/me", nil, nil)
fmt.Println(me["subject_type"], me["credits"])
JsonNode me = api("GET", "/me", null, null);
System.out.println(me.get("subject_type") + " " + me.get("credits"));
me = api("GET", "/me")
puts [me["subject_type"], me["credits"]].inspect
$me = api("GET", "/me");
echo $me["subject_type"], " ", $me["credits"] ?? "", "\n";
var me = await Api.Call("GET", "/me");
Console.WriteLine($"{me!["subject_type"]} {me["credits"]}");
Step 4 — POST /estimate
Free. The body is the run input itself, the bare object (never wrapped in {"input": ...}). hold_credits is a reservation, not the price; min_credits is what the balance must cover; model_alias reads gpt-terra.
# input.json: the run input object - {"task": "sort-sighting", "sighting": "when: at night, well after dusk\nhow long: not sure\n...", "notes": "none", "fit_table": "S1 lantern (sky lanterns) | fits 4 of 4 known: ..."}
# - see the field table
api POST /estimate "$(cat input.json)" | jq '.data | {hold_credits, min_credits, model, model_alias, markup_bps, warnings}'
inp = json.load(open("input.json")) # {"task": "sort-sighting", "sighting": "when: at night, well after dusk\nhow long: not sure\n...", "notes": "none", "fit_table": "S1 lantern (sky lanterns) | fits 4 of 4 known: ..."}
# - see the field table
est = api("POST", "/estimate", inp)
print(est["hold_credits"], est["min_credits"], est["model"], est.get("warnings"))
import { readFileSync } from "node:fs";
const input = JSON.parse(readFileSync("input.json", "utf8")); // {task: "sort-sighting", sighting, notes, fit_table} (see the field table)
const est = await api("POST", "/estimate", input);
console.log(est.hold_credits, est.min_credits, est.model, est.warnings);
raw, _ := os.ReadFile("input.json") // add "os" to the imports
var input map[string]any
json.Unmarshal(raw, &input)
est, _ := api("POST", "/estimate", input, nil)
fmt.Println(est["hold_credits"], est["min_credits"], est["model"])
Map<String, Object> input = M.readValue(new java.io.File("input.json"), Map.class);
JsonNode est = api("POST", "/estimate", input, null);
System.out.println(est.get("hold_credits") + " " + est.get("min_credits") + " " + est.get("model"));
input = JSON.parse(File.read("input.json"))
est = api("POST", "/estimate", input)
puts [est["hold_credits"], est["min_credits"], est["model"]].inspect
$input = json_decode(file_get_contents("input.json"), true);
$est = api("POST", "/estimate", $input);
echo $est["hold_credits"], " ", $est["min_credits"], " ", $est["model"], "\n";
var input = JsonNode.Parse(File.ReadAllText("input.json"))!;
var est = await Api.Call("POST", "/estimate", input);
Console.WriteLine($"{est!["hold_credits"]} {est["min_credits"]} {est["model"]}");
Step 5 — POST /run, then poll the job
Send an Idempotency-Key built from the lane and the input: a retry with the same key never bills twice. The page uses what-was-that:<task>:<inputHash>:a<attempt> (the one task is sort-sighting), and its one reformat retry (with retry_note added) is attempt 2, a new key and a second run. The job's output.output is the reply text; truncated: true means the balance cut it short.
KEY="what-was-that:sort-sighting:$(shasum -a 256 input.json | cut -c1-16):a1"
JOB=$(curl -s -X POST "$BASE/run" -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" \
-H "Idempotency-Key: $KEY" --data @input.json | jq -r '.data.job_id')
while :; do
J=$(api GET "/jobs/$JOB"); S=$(echo "$J" | jq -r '.data.status')
case "$S" in succeeded|failed|cancelled) break;; esac; sleep 2
done
echo "$J" | jq -r '.data.output.output' > reply.json # one JSON object, the reply contract
echo "$J" | jq '.data | {charged_credits, truncated}'
import hashlib, time
key = "what-was-that:" + inp["task"] + ":" + hashlib.sha256(json.dumps(inp).encode()).hexdigest()[:16] + ":a1"
job = api("POST", "/run", inp, {"Idempotency-Key": key})
while True:
j = api("GET", "/jobs/" + job["job_id"])
if j["status"] in ("succeeded", "failed", "cancelled"):
break
time.sleep(2)
reply = json.loads(j["output"]["output"]) # the reply as one JSON object
print(j["charged_credits"], j.get("truncated"), reply.get("verdict"))
import { createHash } from "node:crypto";
const key = `what-was-that:${input.task}:${createHash("sha256").update(JSON.stringify(input)).digest("hex").slice(0, 16)}:a1`;
const job = await api("POST", "/run", input, { "Idempotency-Key": key });
let j;
do { await new Promise((r) => setTimeout(r, 2000)); j = await api("GET", "/jobs/" + job.job_id); }
while (!["succeeded", "failed", "cancelled"].includes(j.status));
const reply = JSON.parse(j.output.output);
console.log(j.charged_credits, j.truncated, reply.verdict);
sum := sha256.Sum256(raw) // add "crypto/sha256", "encoding/hex", "time" to the imports
key := "what-was-that:" + input["task"].(string) + ":" + hex.EncodeToString(sum[:8]) + ":a1"
job, _ := api("POST", "/run", input, map[string]string{"Idempotency-Key": key})
var j map[string]any
for {
time.Sleep(2 * time.Second)
j, _ = api("GET", "/jobs/"+job["job_id"].(string), nil, nil)
if s := j["status"]; s == "succeeded" || s == "failed" || s == "cancelled" { break }
}
fmt.Println(j["charged_credits"], j["truncated"], j["output"].(map[string]any)["output"])
var digest = java.security.MessageDigest.getInstance("SHA-256").digest(M.writeValueAsBytes(input));
String key = "what-was-that:" + input.get("task") + ":" + HexFormat.of().formatHex(digest, 0, 8) + ":a1";
JsonNode job = api("POST", "/run", input, Map.of("Idempotency-Key", key)), j;
do { Thread.sleep(2000); j = api("GET", "/jobs/" + job.get("job_id").asText(), null, null); }
while (!Set.of("succeeded", "failed", "cancelled").contains(j.get("status").asText()));
JsonNode reply = M.readTree(j.get("output").get("output").asText());
System.out.println(j.get("charged_credits") + " " + reply);
require "digest"
key = "what-was-that:#{input["task"]}:#{Digest::SHA256.hexdigest(JSON.generate(input))[0, 16]}:a1"
job = api("POST", "/run", input, { "Idempotency-Key" => key })
j = nil
loop do
sleep 2
j = api("GET", "/jobs/#{job["job_id"]}")
break if %w[succeeded failed cancelled].include?(j["status"])
end
reply = JSON.parse(j["output"]["output"])
puts [j["charged_credits"], j["truncated"], reply["verdict"]].inspect
$key = "what-was-that:" . $input["task"] . ":" . substr(hash("sha256", json_encode($input)), 0, 16) . ":a1";
$job = api("POST", "/run", $input, ["Idempotency-Key" => $key]);
do { sleep(2); $j = api("GET", "/jobs/" . $job["job_id"]); }
while (!in_array($j["status"], ["succeeded", "failed", "cancelled"]));
$reply = json_decode($j["output"]["output"], true);
echo $j["charged_credits"], " ", $reply["verdict"], "\n";
var digest = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(input.ToJsonString()));
var key = $"what-was-that:{input["task"]}:{Convert.ToHexString(digest, 0, 8).ToLowerInvariant()}:a1";
var job = await Api.Call("POST", "/run", input, new() { ["Idempotency-Key"] = key });
JsonNode j;
do { await Task.Delay(2000); j = (await Api.Call("GET", "/jobs/" + job!["job_id"]))!; }
while (!new[] { "succeeded", "failed", "cancelled" }.Contains(j["status"]!.GetValue<string>()));
var reply = JsonNode.Parse(j["output"]!["output"]!.GetValue<string>());
Console.WriteLine($"{j["charged_credits"]} {reply}");
Step 6 — POST /run-stream
The same run as Server-Sent Events, with the same input.json. Browsers receive progress ticks rather than text deltas; the final done event carries the reply.
# Server-Sent Events: tick/delta events while the job runs, then a final event with the job
curl -N -s -X POST "$BASE/run-stream" -H "Content-Type: application/json" -H "Authorization: Bearer $TOKEN" \
-H "Idempotency-Key: what-was-that:sort-sighting:$(shasum -a 256 input.json | cut -c1-16):a1" --data @input.json
rev = json.load(open("input.json")) # the same run input as input.json: {"task": "sort-sighting", "sighting": "when: at night, well after dusk\nhow long: not sure\n...", "notes": "none", "fit_table": "S1 lantern (sky lanterns) | fits 4 of 4 known: ..."}
# - see the field table
req = urllib.request.Request(BASE + "/run-stream", method="POST", data=json.dumps(rev).encode(),
headers={"Content-Type": "application/json", "Authorization": "Bearer " + TOKEN,
"Idempotency-Key": "what-was-that:sort-sighting:" + hashlib.sha256(json.dumps(rev).encode()).hexdigest()[:16] + ":a1"})
with urllib.request.urlopen(req) as r:
for line in r:
line = line.decode().strip()
if line.startswith("data:"):
print(line[5:].strip()[:200])
const rev = JSON.parse(readFileSync("input.json", "utf8"));
const r = await fetch(BASE + "/run-stream", { method: "POST", body: JSON.stringify(rev), headers: {
"Content-Type": "application/json", Authorization: "Bearer " + TOKEN,
"Idempotency-Key": `what-was-that:sort-sighting:${createHash("sha256").update(JSON.stringify(rev)).digest("hex").slice(0, 16)}:a1` } });
const dec = new TextDecoder();
for await (const chunk of r.body) for (const line of dec.decode(chunk).split("\n"))
if (line.startsWith("data:")) console.log(line.slice(5).trim().slice(0, 200));
rraw, _ := os.ReadFile("input.json") // add "bufio", "strings" to the imports
rs := sha256.Sum256(rraw)
req, _ := http.NewRequest("POST", base+"/run-stream", bytes.NewReader(rraw))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Idempotency-Key", "what-was-that:sort-sighting:"+hex.EncodeToString(rs[:8])+":a1")
res, _ := http.DefaultClient.Do(req)
sc := bufio.NewScanner(res.Body)
for sc.Scan() { if l := sc.Text(); strings.HasPrefix(l, "data:") { fmt.Println(l[5:]) } }
String rev = java.nio.file.Files.readString(java.nio.file.Path.of("input.json"));
var rd = java.security.MessageDigest.getInstance("SHA-256").digest(rev.getBytes());
var sreq = HttpRequest.newBuilder(URI.create(BASE + "/run-stream")).header("Content-Type", "application/json")
.header("Authorization", "Bearer " + token).header("Idempotency-Key", "what-was-that:sort-sighting:" + HexFormat.of().formatHex(rd, 0, 8) + ":a1")
.POST(HttpRequest.BodyPublishers.ofString(rev)).build();
C.send(sreq, HttpResponse.BodyHandlers.ofLines()).body().filter(l -> l.startsWith("data:")).forEach(System.out::println);
rev = File.read("input.json")
uri = URI(BASE + "/run-stream")
req = Net::HTTP::Post.new(uri, "Content-Type" => "application/json", "Authorization" => "Bearer #{TOKEN}",
"Idempotency-Key" => "what-was-that:sort-sighting:#{Digest::SHA256.hexdigest(rev)[0, 16]}:a1")
req.body = rev
Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |h|
h.request(req) { |res| res.read_body { |chunk| chunk.each_line { |l| puts l if l.start_with?("data:") } } }
end
$rev = file_get_contents("input.json");
$ch = curl_init(BASE . "/run-stream");
curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => $rev, CURLOPT_HTTPHEADER => [
"Content-Type: application/json", "Authorization: Bearer $TOKEN",
"Idempotency-Key: what-was-that:sort-sighting:" . substr(hash("sha256", $rev), 0, 16) . ":a1"],
CURLOPT_WRITEFUNCTION => function ($ch, $chunk) { foreach (explode("\n", $chunk) as $l) if (str_starts_with($l, "data:")) echo $l, "\n"; return strlen($chunk); }]);
curl_exec($ch);
var rev = File.ReadAllText("input.json");
var rd = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(rev));
var sreq = new HttpRequestMessage(HttpMethod.Post, Api.Base + "/run-stream") { Content = new StringContent(rev, System.Text.Encoding.UTF8, "application/json") };
sreq.Headers.Add("Authorization", "Bearer " + Api.Token);
sreq.Headers.Add("Idempotency-Key", $"what-was-that:sort-sighting:{Convert.ToHexString(rd, 0, 8).ToLowerInvariant()}:a1");
using var http = new HttpClient();
using var res = await http.SendAsync(sreq, HttpCompletionOption.ResponseHeadersRead);
using var rdr = new StreamReader(await res.Content.ReadAsStreamAsync());
for (string? l; (l = await rdr.ReadLineAsync()) != null;) if (l.StartsWith("data:")) Console.WriteLine(l);