Color Blindness Simulator API
The simulated views, the color measurements, the list of colliding pairs, the tested fixes and every download run free in the browser and need no API. The API is for the one metered step: send the colors and pairs the page measured and an optional note, and get back, as JSON, a color critique covering contrast, palette coherence, meaning carried by color and color blindness. The picture itself is never sent. The page builds this input for you and checks the reply against its own numbers.
Base URL: https://api.skillsafe.ai/v1/app-api. Every response is {"data": ...} or {"error": {"code", "message"}}; read error.code and error.message rather than the HTTP status alone.
The task field
This app has one task. Always send "task": "critique".
| task | What it does | Reply |
|---|---|---|
critique | Reads a screen's measured colors and color pairs and returns a verdict, a summary, four rated dimensions (contrast, palette_coherence, semantic_use, accessibility) with observation, problem and fix, notes on the pairs that matter, and checks to make on the real screen. It does not invent ratios or colors. | One JSON object |
Input fields
Every field is a string; colors, pairs and counts hold JSON text.
| Field | Meaning |
|---|---|
task | "critique" |
severity_pct | Simulated strength, 10 to 100 (100 = full dichromacy). |
page_verdict | pass, minor_issue or major_issue, from the measurements. |
colors | List of {id, hex, share_pct, lightness, chroma, neutral}, largest first, at most 12. |
pairs | List of {id, a, b, touching, contrast, low_contrast, de, status, page_fix}, at most 24, most serious first. de holds CIEDE2000 differences: normal, protan, deutan, tritan, achroma. status per type is same, close or ok. |
counts | {red_blind, green_blind, blue_blind, grayscale: {same, close}, low_contrast_touching}. |
note | Optional: what the screen is and what its colors mean (at most 1,000 characters). |
clipped_note | Empty, or sentences saying which part of the input was cut. |
The reply
job.output.output is text holding one JSON object: verdict, summary (2 to 4 sentences), dimensions (exactly four: contrast, palette_coherence, semantic_use, accessibility, each {id, rating, observation, problem, fix}), pairs (at most 8 {id, note, fix}) and checks (1 to 4 strings). Before showing it, check that pair ids are ones you sent and that ratios and hexes appear in your input, as the page does. If the balance ran low, truncated is true and the object may stop early; the page keeps every part that arrived whole.
Worked example
Input (input.json), from the page's "Line chart" example:
{
"task": "critique",
"severity_pct": "100",
"page_verdict": "major_issue",
"colors": "[{\"id\":\"C1\",\"hex\":\"#ffffff\",\"share_pct\":94.5,\"lightness\":100,\"chroma\":0,\"neutral\":true},{\"id\":\"C2\",\"hex\":\"#ff7f0e\",\"share_pct\":1.2,\"lightness\":67,\"chroma\":84,\"neutral\":false},{\"id\":\"C3\",\"hex\":\"#d62728\",\"share_pct\":1.2,\"lightness\":47,\"chroma\":79,\"neutral\":false},{\"id\":\"C4\",\"hex\":\"#2ca02c\",\"share_pct\":1.1,\"lightness\":58,\"chroma\":73,\"neutral\":false},{\"id\":\"C5\",\"hex\":\"#282828\",\"share_pct\":0.9,\"lightness\":16,\"chroma\":0,\"neutral\":true},{\"id\":\"C6\",\"hex\":\"#555555\",\"share_pct\":0.6,\"lightness\":36,\"chroma\":0,\"neutral\":true},{\"id\":\"C7\",\"hex\":\"#666666\",\"share_pct\":0.6,\"lightness\":43,\"chroma\":0,\"neutral\":true}]",
"pairs": "[{\"id\":\"P1\",\"a\":\"C2\",\"b\":\"C4\",\"touching\":false,\"contrast\":1.34,\"low_contrast\":false,\"de\":{\"normal\":55.2,\"protan\":1.4,\"deutan\":14.5,\"tritan\":63.3,\"achroma\":7.8},\"status\":{\"protan\":\"same\",\"deutan\":\"ok\",\"tritan\":\"ok\",\"achroma\":\"close\"},\"page_fix\":{\"change\":\"C4\",\"from\":\"#2ca02c\",\"to\":\"#79ad6f\",\"min_de_after\":12.1,\"contrast_after\":1.03}},{\"id\":\"P2\",\"a\":\"C3\",\"b\":\"C4\",\"touching\":false,\"contrast\":1.47,\"low_contrast\":false,\"de\":{\"normal\":71.8,\"protan\":24.9,\"deutan\":4.8,\"tritan\":65.3,\"achroma\":10.8},\"status\":{\"protan\":\"ok\",\"deutan\":\"same\",\"tritan\":\"ok\",\"achroma\":\"ok\"},\"page_fix\":{\"change\":\"C4\",\"from\":\"#2ca02c\",\"to\":\"#6ea365\",\"min_de_after\":12.9,\"contrast_after\":1.69}},{\"id\":\"P3\",\"a\":\"C3\",\"b\":\"C6\",\"touching\":false,\"contrast\":1.48,\"low_contrast\":false,\"de\":{\"normal\":30.1,\"protan\":18,\"deutan\":27.6,\"tritan\":32.1,\"achroma\":9.6},\"status\":{\"protan\":\"ok\",\"deutan\":\"ok\",\"tritan\":\"ok\",\"achroma\":\"close\"}},{\"id\":\"P4\",\"a\":\"C3\",\"b\":\"C7\",\"touching\":false,\"contrast\":1.14,\"low_contrast\":false,\"de\":{\"normal\":28.7,\"protan\":18.8,\"deutan\":24.9,\"tritan\":30.3,\"achroma\":3.5},\"status\":{\"protan\":\"ok\",\"deutan\":\"ok\",\"tritan\":\"ok\",\"achroma\":\"same\"}},{\"id\":\"P5\",\"a\":\"C1\",\"b\":\"C2\",\"touching\":true,\"contrast\":2.53,\"low_contrast\":true,\"de\":{\"normal\":36.5,\"protan\":38.1,\"deutan\":33.6,\"tritan\":37.1,\"achroma\":22},\"status\":{\"protan\":\"ok\",\"deutan\":\"ok\",\"tritan\":\"ok\",\"achroma\":\"ok\"}},{\"id\":\"P6\",\"a\":\"C1\",\"b\":\"C3\",\"touching\":true,\"contrast\":5.02,\"low_contrast\":false,\"de\":{\"normal\":48.7,\"protan\":52.9,\"deutan\":42,\"tritan\":47.4,\"achroma\":39.5},\"status\":{\"protan\":\"ok\",\"deutan\":\"ok\",\"tritan\":\"ok\",\"achroma\":\"ok\"}},{\"id\":\"P7\",\"a\":\"C1\",\"b\":\"C4\",\"touching\":true,\"contrast\":3.4,\"low_contrast\":false,\"de\":{\"normal\":40.4,\"protan\":37.6,\"deutan\":37.9,\"tritan\":38.2,\"achroma\":29.5},\"status\":{\"protan\":\"ok\",\"deutan\":\"ok\",\"tritan\":\"ok\",\"achroma\":\"ok\"}},{\"id\":\"P8\",\"a\":\"C1\",\"b\":\"C5\",\"touching\":true,\"contrast\":14.74,\"low_contrast\":false,\"de\":{\"normal\":75.9,\"protan\":75.9,\"deutan\":75.9,\"tritan\":75.9,\"achroma\":75.9},\"status\":{\"protan\":\"ok\",\"deutan\":\"ok\",\"tritan\":\"ok\",\"achroma\":\"ok\"}},{\"id\":\"P9\",\"a\":\"C1\",\"b\":\"C7\",\"touching\":true,\"contrast\":5.74,\"low_contrast\":false,\"de\":{\"normal\":43.1,\"protan\":43.1,\"deutan\":43.1,\"tritan\":43.1,\"achroma\":43.1},\"status\":{\"protan\":\"ok\",\"deutan\":\"ok\",\"tritan\":\"ok\",\"achroma\":\"ok\"}},{\"id\":\"P10\",\"a\":\"C1\",\"b\":\"C6\",\"touching\":true,\"contrast\":7.45,\"low_contrast\":false,\"de\":{\"normal\":50.6,\"protan\":50.6,\"deutan\":50.6,\"tritan\":50.6,\"achroma\":50.6},\"status\":{\"protan\":\"ok\",\"deutan\":\"ok\",\"tritan\":\"ok\",\"achroma\":\"ok\"}}]",
"counts": "{\"red_blind\":{\"same\":1,\"close\":0},\"green_blind\":{\"same\":1,\"close\":0},\"blue_blind\":{\"same\":0,\"close\":0},\"grayscale\":{\"same\":1,\"close\":2},\"low_contrast_touching\":1}",
"note": "Quarterly line chart in a sales deck. Red is sales, green is costs, orange is profit; the legend is the only label.",
"clipped_note": ""
}
Reply:
{"verdict":"major_issue","summary":"Per the note, the three series are told apart by hue alone, and two of the three collapse for color-blind viewers: orange profit (C2) and green costs (C4) look the same to red-blind viewers, and red sales (C3) and green costs look the same to green-blind viewers. The orange line is also faint on the white background at 2.53:1. The most important fix is to label each line directly at its end instead of relying on the legend, then adjust the green.","dimensions":[{"id":"contrast","rating":"minor_issue","observation":"Against white C1 #ffffff: dark gray C5 #282828 is 14.74:1, C6 #555555 is 7.45:1, C7 #666666 is 5.74:1, red C3 #d62728 is 5.02:1, green C4 #2ca02c is 3.4:1 and orange C2 #ff7f0e is 2.53:1. One touching pair is under 3:1.","problem":"P5 (orange C2 on white C1) at 2.53:1 is below the 3:1 a chart line needs, so the profit line is the weakest mark on the slide, especially on a projector. If C4 green is used for text it also falls short of 4.5:1 at 3.4:1.","fix":"Make the orange profit line darker (keep the hue, lower its lightness) until it clears 3:1 on white, and thicken all three lines."},{"id":"palette_coherence","rating":"pass","observation":"Three saturated non-neutral colors (orange C2 lightness 67, red C3 lightness 47, green C4 lightness 58, chroma 73 to 84) plus white and three grays. Normal-vision differences between series are large: 55.2 for C2/C4 and 71.8 for C3/C4.","problem":"","fix":""},{"id":"semantic_use","rating":"major_issue","observation":"The note says red is sales, green is costs, orange is profit, and the legend is the only label, so series identity is carried by hue alone.","problem":"Readers must match each line to a legend swatch by color. When P1 or P2 collapse, a red- or green-blind viewer cannot tell which line is costs, which is the main message of a sales vs costs chart.","fix":"Put the series name (Sales, Costs, Profit) directly at the end of each line and give the lines different dash patterns or markers, so the legend is no longer needed to read them."},{"id":"accessibility","rating":"major_issue","observation":"P1 (orange C2 vs green C4) is same for red-blind viewers, difference 1.4. P2 (red C3 vs green C4) is same for green-blind viewers, difference 4.8. In grayscale P4 (C3 vs C7) is same at 3.5 and P1 and P3 are close.","problem":"Two of the three series pairs merge for the most common forms of color blindness, so many color-blind viewers in the audience cannot read the chart from the legend.","fix":"Use the page's tested replacement for green C4: #6ea365 lifts the red-green pair P2 to a smallest difference of 12.9; #79ad6f lifts P1 to 12.1. Pick one, re-check the other pair, and add direct labels either way."}],"pairs":[{"id":"P1","note":"Orange C2 #ff7f0e (profit) and green C4 #2ca02c (costs) differ by 55.2 normally but only 1.4 for red-blind viewers, so they look the same; contrast between them is 1.34:1.","fix":"Change C4 to the tested #79ad6f (smallest difference after 12.1), and label both lines directly."},{"id":"P2","note":"Red C3 #d62728 (sales) and green C4 #2ca02c (costs) differ by 71.8 normally but only 4.8 for green-blind viewers, so they look the same.","fix":"Change C4 to the tested #6ea365 (smallest difference after 12.9, contrast 1.69:1 between the pair), and use a dashed line for costs."},{"id":"P5","note":"Orange C2 #ff7f0e on white C1 #ffffff is 2.53:1, under the 3:1 a chart line needs.","fix":"Darken the orange and make the line thicker so profit stays visible on white."},{"id":"P4","note":"Red C3 #d62728 and gray C7 #666666 are same only in grayscale (difference 3.5); this matters for black-and-white printing and complete color blindness, not for red-, green- or blue-blind viewers (ok for all three).","fix":"If C7 is a gridline or axis near the sales line, make it lighter so the sales line stands out in a printed copy."}],"checks":["Which of the gray colors C5, C6 and C7 are axis labels or body text, and whether C7 at 5.74:1 is used for small text.","Whether the slide will be printed in grayscale, where P4 and P1 also merge.","After changing C4, that red, green and orange are still distinct in the simulator for all three types."]}
Errors
| HTTP | What to do |
|---|---|
| 401 | The token is missing, expired or a guest token on a run. Get a personal token on the token page. |
| 402 | The balance is below what the run reserves. Top up at skillsafe.ai/account/billing. |
| 400 | The body is not a JSON object of the fields above. |
| 429 | Wait and retry with the same Idempotency-Key. |
Step 1 — a tiny client helper
One function that sends JSON and unwraps the {data, error} envelope.
BASE="https://api.skillsafe.ai/v1/app-api"
TOKEN="paste-your-token-here" # from https://color-blindness-simulator.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://color-blindness-simulator.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"]// color-blindness-simulator.mjs -- Node 18+ (global fetch)
const BASE = "https://api.skillsafe.ai/v1/app-api";
let TOKEN = "paste-your-token-here"; // from https://color-blindness-simulator.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://color-blindness-simulator.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
}// ColorBlindnessSimulator.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 ColorBlindnessSimulator {
static final String BASE = "https://api.skillsafe.ai/v1/app-api";
static String token = "paste-your-token-here"; // from https://color-blindness-simulator.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://color-blindness-simulator.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://color-blindness-simulator.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://color-blindness-simulator.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 your personal token: sign in on the token page and copy it.
# 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":"color-blindness-simulator"}' | 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": "color-blindness-simulator"})["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: "color-blindness-simulator" })).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": "color-blindness-simulator"}, 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", "color-blindness-simulator"), 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: "color-blindness-simulator" })["token"])// a guest token (enough for /me and /estimate); a run needs your personal token from /tokens.html
$TOKEN = "";
$TOKEN = api("POST", "/guest", ["slug" => "color-blindness-simulator"])["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 = "color-blindness-simulator" }))!["token"]!.GetValue<string>();Step 3 — who am I, and my balance
subject_type is guest or user; credits is the balance (1 credit = $0.0001).
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 — price a run for free
/estimate charges nothing and starts no job. hold_credits is the amount reserved while a run is in flight, not the price; the run is charged what it uses.
# input.json: the run input object - {"task": "critique", "severity_pct": "100", "page_verdict": "major_issue", "colors": "[...]", "pairs": "[...]", "counts": "{...}", "note": "", "clipped_note": ""}
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": "critique", "severity_pct": "100", "page_verdict": "major_issue", "colors": "[...]", "pairs": "[...]", "counts": "{...}", "note": "", "clipped_note": ""}
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, severity_pct, page_verdict, colors, pairs, counts, note, clipped_note}
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 — run it and wait for the job
Send an Idempotency-Key derived from the input: a retry with the same key is never billed twice.
KEY="color-blindness-simulator:critique:$(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: verdict, summary, dimensions, pairs, checks
echo "$J" | jq '.data | {charged_credits, truncated}' import hashlib, time
key = "color-blindness-simulator:" + 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"]) # {verdict, summary, dimensions, pairs, checks}
print(j["charged_credits"], j.get("truncated"), reply.get("summary"))import { createHash } from "node:crypto";
const key = `color-blindness-simulator:${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.summary);sum := sha256.Sum256(raw) // add "crypto/sha256", "encoding/hex", "time" to the imports
key := "color-blindness-simulator:" + 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 = "color-blindness-simulator:" + 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 = "color-blindness-simulator:#{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["summary"]].inspect$key = "color-blindness-simulator:" . $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["summary"], "\n";var digest = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(input.ToJsonString()));
var key = $"color-blindness-simulator:{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 — or stream it
/run-stream sends Server-Sent Events while the job runs and the finished job at the end.
# 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: color-blindness-simulator:critique:$(shasum -a 256 input.json | cut -c1-16):a1" --data @input.jsonrin = json.load(open("input.json")) # {"task": "critique", "severity_pct": "100", "page_verdict": "major_issue", "colors": "[...]", "pairs": "[...]", "counts": "{...}", "note": "", "clipped_note": ""}
req = urllib.request.Request(BASE + "/run-stream", method="POST", data=json.dumps(rin).encode(),
headers={"Content-Type": "application/json", "Authorization": "Bearer " + TOKEN,
"Idempotency-Key": "color-blindness-simulator:critique:" + hashlib.sha256(json.dumps(rin).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 rin = JSON.parse(readFileSync("input.json", "utf8"));
const r = await fetch(BASE + "/run-stream", { method: "POST", body: JSON.stringify(rin), headers: {
"Content-Type": "application/json", Authorization: "Bearer " + TOKEN,
"Idempotency-Key": `color-blindness-simulator:critique:${createHash("sha256").update(JSON.stringify(rin)).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", "color-blindness-simulator:critique:"+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 rin = java.nio.file.Files.readString(java.nio.file.Path.of("input.json"));
var rd = java.security.MessageDigest.getInstance("SHA-256").digest(rin.getBytes());
var sreq = HttpRequest.newBuilder(URI.create(BASE + "/run-stream")).header("Content-Type", "application/json")
.header("Authorization", "Bearer " + token).header("Idempotency-Key", "color-blindness-simulator:critique:" + HexFormat.of().formatHex(rd, 0, 8) + ":a1")
.POST(HttpRequest.BodyPublishers.ofString(rin)).build();
C.send(sreq, HttpResponse.BodyHandlers.ofLines()).body().filter(l -> l.startsWith("data:")).forEach(System.out::println);rin = File.read("input.json")
uri = URI(BASE + "/run-stream")
req = Net::HTTP::Post.new(uri, "Content-Type" => "application/json", "Authorization" => "Bearer #{TOKEN}",
"Idempotency-Key" => "color-blindness-simulator:critique:#{Digest::SHA256.hexdigest(rin)[0, 16]}:a1")
req.body = rin
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$rin = file_get_contents("input.json");
$ch = curl_init(BASE . "/run-stream");
curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => $rin, CURLOPT_HTTPHEADER => [
"Content-Type: application/json", "Authorization: Bearer $TOKEN",
"Idempotency-Key: color-blindness-simulator:critique:" . substr(hash("sha256", $rin), 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 rin = File.ReadAllText("input.json");
var rd = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(rin));
var sreq = new HttpRequestMessage(HttpMethod.Post, Api.Base + "/run-stream") { Content = new StringContent(rin, System.Text.Encoding.UTF8, "application/json") };
sreq.Headers.Add("Authorization", "Bearer " + Api.Token);
sreq.Headers.Add("Idempotency-Key", $"color-blindness-simulator:critique:{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);