Run FBA Fee Calculator from your own code
The one metered task, review, is available over HTTP. It takes one product's numbers as the page has already computed them - selling price, product cost, size tier, shipping weight, the referral, fulfillment and storage fees, profit, margin, ROI, break-even price, the packaging what-ifs and the page's checks - and returns a verdict, the changes worth making ranked by value, the risks to check and the data that is MISSING.
The division of labour first: the browser does all the arithmetic - size tier, dimensional weight, every fee, profit, margin, ROI, break-even price, the price for a target margin and the packaging what-ifs - and writes the copy, the CSV and the Markdown. That part is free and never calls the API. Only the review is metered: model alias llm-default, billed per run at the model's price plus a 10% markup. The page re-checks every number the review proposes before it shows anything - see How the page checks the reply.
Base URL and the response shape
Every endpoint lives under https://api.skillsafe.ai/v1/app-api, and every response has one shape:
{ "ok": true, "data": { ... } }
{ "ok": false, "error": { "code": "...", "message": "..." } }
The token is minted for this app (the guest call takes {"slug":"fba-fee-calculator"}), 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 key (task, product) 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: the review 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 and the input
There is one task. Always send it.
| Field | Type | Required | What it holds |
|---|---|---|---|
task | string | yes | Always "review". |
product | string | yes | The computed product as a JSON-encoded string (the input schema takes scalars only) - see below. |
note | string | no | Up to 600 characters: what the product is, competing prices, your plans. |
Inside product
rates, price, product_cost (or null), inbound_per_unit, other_per_unit, category, dimensions_in (long, med, short), unit_weight_lb, size_tier, shipping_weight_lb, shipping_weight_basis (unit or dimensional), fees (referral, referral_pct, fulfillment, storage, storage_months, storage_season, amazon_total), landed_cost, profit, net_margin_pct, roi_pct, break_even_price, target_margin_pct, price_for_target, max_cost_for_target, monthly (units, profit, or null), page_verdict, whatifs (each id, kind, change, saving_per_unit), checks (the page's findings as sentences) and missing.
The reply
output.output on the finished job is a string holding one JSON object:
{
"verdict": "Worth selling" | "Thin margin" | "Losing money" | "Missing data",
"summary": "2-3 sentences",
"levers": [ { "kind": "price" | "product_cost" | "packaging" | "weight" | "inbound" | "storage" | "referral",
"whatif": "w1" | "", "value": 14.53 | null, "action": "one sentence", "reason": "one sentence" } ],
"risks": ["..."], "missing": ["... MISSING ..."]
}
Levers come most valuable first, 1 to 5 of them. value is the new price, product cost, inbound cost or months in storage the lever proposes. The model is told never to invent competitor prices, sales, ad costs, return rates or fee rules, and to quote a packaging saving only from the page's what-ifs.
How the page checks the reply
- The verdict shown is the page's own; a reply that disagrees is flagged.
- A saving is shown only when the lever names one of the page's what-ifs; any other id is flagged and shows no saving.
- Every proposed price, product cost, inbound cost or storage time is re-priced with the same calculator and shown as a page check (profit before and after, new margin).
- A proposed price below the break-even price, a what-if worth $0.25 or more that the review ignored, and an unknown lever kind are all flagged.
- A reply cut short keeps every complete lever that arrived and says how many parts were recovered.
Worked example - a phone stand at $12.99
| Computed by the page | Value |
|---|---|
| Size tier | Large standard, billed at 0.35 lb (dimensional weight) |
| Referral fee | $1.04 (8%) |
| FBA fulfillment fee | $3.90 |
| Profit per unit | $1.49 (11.47% margin) |
| Break-even price | $11.37 |
Request body (input.json):
{"task": "review", "product": "{\"rates\":\"Amazon US rate card 2025, items priced $10-$50\",\"price\":12.99,\"product_cost\":6.2,\"inbound_per_unit\":0.35,\"other_per_unit\":0,\"category\":\"Consumer electronics\",\"dimensions_in\":{\"long\":6.3,\"med\":3.9,\"short\":0.9},\"unit_weight_lb\":0.25,\"size_tier\":\"Large standard\",\"shipping_weight_lb\":0.35,\"shipping_weight_basis\":\"dimensional\",\"fees\":{\"referral\":1.04,\"referral_pct\":8,\"fulfillment\":3.9,\"storage\":0.01,\"storage_months\":1,\"storage_season\":\"January-September\",\"amazon_total\":4.95},\"landed_cost\":6.55,\"profit\":1.49,\"net_margin_pct\":11.47,\"roi_pct\":22.75,\"break_even_price\":11.37,\"target_margin_pct\":20,\"price_for_target\":14.53,\"max_cost_for_target\":5.09,\"monthly\":null,\"page_verdict\":\"Thin margin\",\"whatifs\":[{\"id\":\"w1\",\"kind\":\"packaging\",\"change\":\"Packed shortest side 0.15 in shorter (small standard)\",\"saving_per_unit\":0.75}],\"checks\":[\"Below your 20% target. Net margin is 11.47%. A price of $14.53 reaches 20%, or a product cost of $5.09 at this price.\",\"Billed on size, not weight. The box weighs in at 0.35 lb dimensional against 0.25 lb actual, so the fee follows the box.\",\"Save $0.75 a unit: Packed shortest side 0.15 in shorter (small standard).\"],\"missing\":[]}", "note": "Folding aluminium phone stand in a padded mailer. I want to stay at 12.99 to win the Buy Box."}
A reply (output.output, pretty-printed):
{
"verdict": "Thin margin",
"summary": "At $12.99 the stand earns $1.49 profit per unit, an 11.47% net margin and 22.75% ROI, below your 20% target. Amazon fees take $4.95 of the price, and the $3.90 fulfillment fee is set by the box size because the dimensional weight is 0.35 lb against 0.25 lb actual. Break-even is $11.37, so there is only a small cushion at your chosen price, and monthly demand is MISSING.",
"levers": [
{
"kind": "product_cost",
"whatif": "",
"value": 5.09,
"action": "Ask your supplier for a unit cost of $5.09 so you can keep the price at $12.99 and still reach your 20% target margin.",
"reason": "The page says a product cost of $5.09 at this price reaches the 20% target, against your current $6.20."
},
{
"kind": "packaging",
"whatif": "w1",
"value": null,
"action": "Repack so the shortest side is 0.15 in shorter, which moves the item into the small standard tier.",
"reason": "The page's what-if w1 saves $0.75 a unit against the current $3.90 fulfillment fee."
},
{
"kind": "price",
"whatif": "",
"value": 14.53,
"action": "If you can accept a weaker Buy Box position, test a price near $14.53, which is the page's price for a 20% margin.",
"reason": "You want to stay at $12.99, which is above the $11.37 break-even but gives only an 11.47% margin, so $14.53 is the price that reaches 20%."
}
],
"risks": [
"Advertising spend is not in the page's numbers; check it in your Amazon ad reports before relying on the $1.49 profit per unit.",
"Returns and refunds are not included; check your return report once you have sales, since a thin margin leaves little room.",
"Packing the box 0.15 in thinner may affect protection of the aluminium stand in its padded mailer; test a sample before changing the pack."
],
"missing": [
"Monthly sales volume is MISSING, so total monthly profit and demand cannot be judged.",
"Advertising cost per unit is MISSING and would reduce the $1.49 profit.",
"Return rate is MISSING and would reduce the real profit."
]
}
Step 1 — a tiny client helper
One function that sends JSON and unwraps the response. 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="YOUR_TOKEN" # from https://fba-fee-calculator.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 = "YOUR_TOKEN" # from https://fba-fee-calculator.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"]
// fba-fee-calculator.mjs -- Node 18+ (global fetch)
const BASE = "https://api.skillsafe.ai/v1/app-api";
let TOKEN = "YOUR_TOKEN"; // from https://fba-fee-calculator.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"; "os")
const base = "https://api.skillsafe.ai/v1/app-api"
var token = os.Getenv("SKILLSAFE_TOKEN") // from https://fba-fee-calculator.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
}
// FbaFeeCalculator.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 FbaFeeCalculator {
static final String BASE = "https://api.skillsafe.ai/v1/app-api";
static String token = "YOUR_TOKEN"; // from https://fba-fee-calculator.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 = +"YOUR_TOKEN" # from https://fba-fee-calculator.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 = "YOUR_TOKEN"; // from https://fba-fee-calculator.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 = "YOUR_TOKEN"; // from https://fba-fee-calculator.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":"fba-fee-calculator"}' | 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": "fba-fee-calculator"})["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: "fba-fee-calculator" })).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": "fba-fee-calculator"}, 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", "fba-fee-calculator"), 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: "fba-fee-calculator" })["token"])
// a guest token (enough for /me and /estimate); a run needs your personal token from /tokens.html
$TOKEN = "";
$TOKEN = api("POST", "/guest", ["slug" => "fba-fee-calculator"])["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 = "fba-fee-calculator" }))!["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 llm-default and markup_bps reads 1000 (10%). Save the worked example's request body as input.json.
# input.json: the run input object - {"task": "review", "product": "<JSON string>", "note": "..."} - see the worked example
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": "review", "product": "<JSON string>", "note": "..."} - see the worked example
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: "review", product: "<JSON string>", 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")
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 task and the input: a retry with the same key never bills twice. The page uses fba-fee-calculator:<task>:<inputHash>:a<attempt> (the one task is review). The job's output.output is the reply text - one JSON object; truncated: true means the balance cut it short, and the complete entries that did arrive are still usable.
KEY="fba-fee-calculator:review:$(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}'
jq -r '"\(.verdict): \(.summary)"' reply.json
jq -r '.levers[]? | "\(.kind): \(.action) - \(.reason)"' reply.json # most valuable first
jq -r '.missing[]? | "MISSING: \(.)"' reply.json
jq -r '.risks[]? | "- \(.)"' reply.json
import hashlib, time
key = "fba-fee-calculator:" + 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"))
print(reply["verdict"], "-", reply["summary"])
for l in reply.get("levers") or []: # most valuable first
print(l["kind"], l["action"], "-", l["reason"])
for n in reply.get("missing") or []:
print("-", n)
import { createHash } from "node:crypto";
const key = `fba-fee-calculator:${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);
console.log(reply.verdict, "-", reply.summary);
for (const l of reply.levers || []) console.log(l.kind, l.action, "-", l.reason); // most valuable first
for (const n of reply.missing || []) console.log("-", n);
sum := sha256.Sum256(raw) // add "crypto/sha256", "encoding/hex", "time" to the imports
key := "fba-fee-calculator:" + 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 }
}
var reply map[string]any
json.Unmarshal([]byte(j["output"].(map[string]any)["output"].(string)), &reply)
fmt.Println(j["charged_credits"], j["truncated"])
fmt.Println(reply["verdict"], "-", reply["summary"])
levers, _ := reply["levers"].([]any) // most valuable first
for _, x := range levers {
r := x.(map[string]any)
fmt.Println(r["kind"], r["action"], "-", r["reason"])
}
notes, _ := reply["missing"].([]any)
for _, n := range notes { fmt.Println("-", n) }
var digest = java.security.MessageDigest.getInstance("SHA-256").digest(M.writeValueAsBytes(input));
String key = "fba-fee-calculator:" + 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") + " " + j.get("truncated"));
System.out.println(reply.path("verdict").asText() + " - " + reply.path("summary").asText());
for (JsonNode r : reply.path("levers")) // most valuable first
System.out.println(r.path("kind").asText() + " " + r.path("action").asText() + " - " + r.path("reason").asText());
for (JsonNode n : reply.path("missing")) System.out.println("- " + n.asText());
require "digest"
key = "fba-fee-calculator:#{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"]].inspect
puts "#{reply["verdict"]} - #{reply["summary"]}"
(reply["levers"] || []).each { |r| puts "#{r["kind"]} #{r["action"]} - #{r["reason"]}" } # most valuable first
(reply["missing"] || []).each { |n| puts "- #{n}" }
$key = "fba-fee-calculator:" . $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"], " ", json_encode($j["truncated"] ?? false), "\n";
echo $reply["verdict"], " - ", $reply["summary"], "\n";
foreach ($reply["levers"] ?? [] as $r) echo $r["kind"], " ", $r["action"], " - ", $r["reason"], "\n"; // most valuable first
foreach ($reply["missing"] ?? [] as $n) echo "- ", $n, "\n";
var digest = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(input.ToJsonString()));
var key = $"fba-fee-calculator:{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"]} {j["truncated"]}");
Console.WriteLine($"{reply["verdict"]} - {reply["summary"]}");
foreach (var r in reply["levers"] as JsonArray ?? new JsonArray()) Console.WriteLine($"{r!["kind"]} {r["action"]} - {r["reason"]}"); // most valuable first
foreach (var n in reply["missing"] as JsonArray ?? new JsonArray()) Console.WriteLine($"- {n}");
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 job, whose output.output is 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: fba-fee-calculator:review:$(shasum -a 256 input.json | cut -c1-16):a1" --data @input.json
rev = json.load(open("input.json")) # the same run input: {"task": "review", "product": "<JSON string>", "note": "..."}
req = urllib.request.Request(BASE + "/run-stream", method="POST", data=json.dumps(rev).encode(),
headers={"Content-Type": "application/json", "Authorization": "Bearer " + TOKEN,
"Idempotency-Key": "fba-fee-calculator:review:" + 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": `fba-fee-calculator:review:${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", "fba-fee-calculator:review:"+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", "fba-fee-calculator:review:" + 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" => "fba-fee-calculator:review:#{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: fba-fee-calculator:review:" . 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", $"fba-fee-calculator:review:{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);