CSV Compare API
The comparison itself - added, removed and changed rows, changed values, column changes - is worked out free in the browser and needs no API. The API is for the one metered step: send the page's comparison and an optional note, and get back a plain-words explanation as JSON.
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": "explain".
| task | What it does |
|---|---|
explain | Reads a comparison of two versions of a CSV file and explains what changed, what looks like a mistake, what to check, and writes a short change note. |
Input fields
| Field | Type | Meaning |
|---|---|---|
task | string | "explain" (required) |
old_name | string | The old file's name, up to 80 characters. |
new_name | string | The new file's name, up to 80 characters. |
context | string | Optional note, up to 1,500 characters: what the files are and what should have changed. The page cuts a longer note at a sentence and says how much was left out. |
facts | string | JSON text of the page's comparison (required): old_file, new_file, matched_by, sentence, counts (old_rows, new_rows, added, removed, changed, unchanged, changed_values, format_only_values, content_values, all formatted strings), columns (compared, added, removed, type_changes, skipped), by_column, changed_values_sample, added_rows_sample and removed_rows_sample (each {shown, of, items}), settings and notes. The model quotes these figures exactly and computes none of its own. |
The reply
job.output.output is text holding one JSON object (sometimes inside a ```json fence): headline (at most 140 characters), summary (2 to 4 sentences), patterns (1 to 5 strings; empty when there are no differences), concerns (0 to 4 strings), checks (2 to 4 strings) and change_note (at most 600 characters). Every figure in it should appear in facts or context; the page flags any that does not. If the balance ran low, truncated is true and the object may stop early; the page keeps every part that arrived whole.
Worked examples
Price list, March vs April (matched by sku)
Input (input.json):
{
"task": "explain",
"old_name": "prices-march.csv",
"new_name": "prices-april.csv",
"context": "Our shop's product list. April prices went to the website on the 1st.",
"facts": "{\"old_file\":\"prices-march.csv\",\"new_file\":\"prices-april.csv\",\"matched_by\":\"sku\",\"sentence\":\"Compared 14 old rows with 15 new rows, matched by sku: 2 rows added, 1 removed, 8 changed, 5 unchanged.\",\"counts\":{\"old_rows\":\"14\",\"new_rows\":\"15\",\"added\":\"2\",\"removed\":\"1\",\"changed\":\"8\",\"unchanged\":\"5\",\"changed_values\":\"8\",\"format_only_values\":\"0\",\"content_values\":\"8\"},\"columns\":{\"compared\":[\"product\",\"category\",\"price\",\"stock\"],\"added\":[],\"removed\":[],\"type_changes\":[],\"skipped\":[]},\"by_column\":[\"product: 1 row: new value\",\"price: 5 rows: all up, +6.7% to +10.0%\",\"stock: 2 rows: all down, -6.2% to -100%\"],\"changed_values_sample\":{\"shown\":8,\"of\":8,\"items\":[{\"key\":\"TEA-001\",\"column\":\"price\",\"old\":\"6.50\",\"new\":\"7.15\",\"change\":\"up 10.0%\"},{\"key\":\"COF-101\",\"column\":\"product\",\"old\":\"House Espresso 250g\",\"new\":\"House Espresso Blend 250g\",\"change\":\"new value\"},{\"key\":\"COF-104\",\"column\":\"stock\",\"old\":\"9\",\"new\":\"0\",\"change\":\"down 100%\"},{\"key\":\"TEA-002\",\"column\":\"price\",\"old\":\"7.00\",\"new\":\"7.70\",\"change\":\"up 10.0%\"},{\"key\":\"ACC-204\",\"column\":\"stock\",\"old\":\"80\",\"new\":\"75\",\"change\":\"down 6.2%\"},{\"key\":\"TEA-003\",\"column\":\"price\",\"old\":\"8.20\",\"new\":\"9.02\",\"change\":\"up 10.0%\"},{\"key\":\"TEA-004\",\"column\":\"price\",\"old\":\"5.40\",\"new\":\"5.94\",\"change\":\"up 10.0%\"},{\"key\":\"ACC-203\",\"column\":\"price\",\"old\":\"15.00\",\"new\":\"16.00\",\"change\":\"up 6.7%\"}]},\"added_rows_sample\":{\"shown\":2,\"of\":2,\"items\":[{\"key\":\"TEA-005\",\"values\":\"sku=TEA-005; product=Rooibos Vanilla 50g; category=Tea; price=6.20; stock=30\"},{\"key\":\"GFT-302\",\"values\":\"sku=GFT-302; product=Coffee Lovers Box; category=Gifts; price=29.00; stock=8\"}]},\"removed_rows_sample\":{\"shown\":1,\"of\":1,\"items\":[{\"key\":\"ACC-205\",\"values\":\"sku=ACC-205; product=Milk Frother; category=Accessories; price=18.00; stock=7\"}]},\"settings\":[\"spaces at the start and end ignored\",\"upper/lower case counts\",\"1.50 and 1.5 count as the same number\"],\"notes\":[]}"
}Reply (job.output.output):
```json
{
"headline": "April raises 5 prices by +6.7% to +10.0%, adds 2 products and drops the Milk Frother (ACC-205).",
"summary": "Compared 14 old rows with 15 new rows, matched by sku: 2 rows added, 1 removed, 8 changed, 5 unchanged. All 8 changed values are real content, none is format only. They are 5 price rises, 2 stock drops and 1 product name change.",
"patterns": [
"Every changed price is up: TEA-001, TEA-002, TEA-003 and TEA-004 each up 10.0%, and ACC-203 up 6.7% (15.00 to 16.00).",
"Stock fell on 2 rows: COF-104 from 9 to 0 (down 100%) and ACC-204 from 80 to 75 (down 6.2%).",
"COF-101 was renamed from House Espresso 250g to House Espresso Blend 250g.",
"Added: TEA-005 Rooibos Vanilla 50g and GFT-302 Coffee Lovers Box. Removed: ACC-205 Milk Frother."
],
"concerns": [
"ACC-205 Milk Frother is gone from the new file and the context does not mention it.",
"COF-104 stock went from 9 to 0, which may mean sold out or a missing count."
],
"checks": [
"Confirm ACC-205 Milk Frother was meant to be removed.",
"Confirm COF-104 really has no stock left.",
"Check that the ACC-203 rise of +6.7% was intended, since the Tea prices all rose by 10.0%."
],
"change_note": "Between prices-march.csv and prices-april.csv, 2 rows were added (TEA-005, GFT-302) and 1 removed (ACC-205 Milk Frother). Of 8 changed rows, 5 have higher prices (+6.7% to +10.0%), 2 have lower stock and COF-101 has a new product name. 5 rows are unchanged."
}
```
Customers after a migration (columns added and removed)
Input (input.json):
{
"task": "explain",
"old_name": "customers-old-crm.csv",
"new_name": "customers-new-system.csv",
"context": "Customer list exported from our old CRM and from the new system after the move. Fax was meant to be dropped.",
"facts": "{\"old_file\":\"customers-old-crm.csv\",\"new_file\":\"customers-new-system.csv\",\"matched_by\":\"customer_id\",\"sentence\":\"Compared 10 old rows with 9 new rows, matched by customer_id: 0 rows added, 1 removed, 9 changed, 0 unchanged. Columns: 1 added, 2 removed.\",\"counts\":{\"old_rows\":\"10\",\"new_rows\":\"9\",\"added\":\"0\",\"removed\":\"1\",\"changed\":\"9\",\"unchanged\":\"0\",\"changed_values\":\"15\",\"format_only_values\":\"14\",\"content_values\":\"1\"},\"columns\":{\"compared\":[\"name\",\"email\",\"phone\",\"signup_date\"],\"added\":[\"country_code\"],\"removed\":[\"country\",\"fax\"],\"type_changes\":[],\"skipped\":[]},\"by_column\":[\"name: 1 row: new value\",\"email: 3 rows: upper/lower case only\",\"phone: 2 rows: spaces only\",\"signup_date: 9 rows: same date, new format\"],\"changed_values_sample\":{\"shown\":15,\"of\":15,\"items\":[{\"key\":\"C-1001\",\"column\":\"signup_date\",\"old\":\"3/14/2024\",\"new\":\"2024-03-14\",\"change\":\"same date, new format\"},{\"key\":\"C-1002\",\"column\":\"email\",\"old\":\"Ben.Carter@Example.com\",\"new\":\"ben.carter@example.com\",\"change\":\"upper/lower case only\"},{\"key\":\"C-1005\",\"column\":\"name\",\"old\":\"Elif Yilmaz\",\"new\":\"Elif Yılmaz\",\"change\":\"new value\"},{\"key\":\"C-1006\",\"column\":\"phone\",\"old\":\"+44 20 5555 0106\",\"new\":\"+442055550106\",\"change\":\"spaces only\"},{\"key\":\"C-1002\",\"column\":\"signup_date\",\"old\":\"4/2/2024\",\"new\":\"2024-04-02\",\"change\":\"same date, new format\"},{\"key\":\"C-1004\",\"column\":\"email\",\"old\":\"DARA.OKAFOR@EXAMPLE.COM\",\"new\":\"dara.okafor@example.com\",\"change\":\"upper/lower case only\"},{\"key\":\"C-1010\",\"column\":\"phone\",\"old\":\"+45 33 55 01 10\",\"new\":\"+4533550110\",\"change\":\"spaces only\"},{\"key\":\"C-1003\",\"column\":\"signup_date\",\"old\":\"4/19/2024\",\"new\":\"2024-04-19\",\"change\":\"same date, new format\"},{\"key\":\"C-1008\",\"column\":\"email\",\"old\":\"Hiro.Tanaka@example.com\",\"new\":\"hiro.tanaka@example.com\",\"change\":\"upper/lower case only\"},{\"key\":\"C-1004\",\"column\":\"signup_date\",\"old\":\"5/7/2024\",\"new\":\"2024-05-07\",\"change\":\"same date, new format\"},{\"key\":\"C-1005\",\"column\":\"signup_date\",\"old\":\"5/30/2024\",\"new\":\"2024-05-30\",\"change\":\"same date, new format\"},{\"key\":\"C-1006\",\"column\":\"signup_date\",\"old\":\"6/11/2024\",\"new\":\"2024-06-11\",\"change\":\"same date, new format\"},{\"key\":\"C-1008\",\"column\":\"signup_date\",\"old\":\"7/23/2024\",\"new\":\"2024-07-23\",\"change\":\"same date, new format\"},{\"key\":\"C-1009\",\"column\":\"signup_date\",\"old\":\"8/15/2024\",\"new\":\"2024-08-15\",\"change\":\"same date, new format\"},{\"key\":\"C-1010\",\"column\":\"signup_date\",\"old\":\"9/2/2024\",\"new\":\"2024-09-02\",\"change\":\"same date, new format\"}]},\"added_rows_sample\":{\"shown\":0,\"of\":0,\"items\":[]},\"removed_rows_sample\":{\"shown\":1,\"of\":1,\"items\":[{\"key\":\"C-1007\",\"values\":\"customer_id=C-1007; name=Greta Lind; email=greta.lind@example.com; phone=+46 8 555 0107; country=Sweden; signup_date=7/1/2024; fax=\"}]},\"settings\":[\"spaces at the start and end ignored\",\"upper/lower case counts\",\"1.50 and 1.5 count as the same number\"],\"notes\":[]}"
}Reply (job.output.output):
```json
{
"headline": "Nearly all changes are format only; C-1007 Greta Lind is gone and country was dropped along with fax.",
"summary": "Compared 10 old rows with 9 new rows, matched by customer_id. All 9 matched rows changed, but 14 of the changed values are format only and 1 is real content, a name edit on C-1005. One row, C-1007, is missing from the new file. The country column was removed along with fax, and country_code was added.",
"patterns": [
"signup_date moved from 3/14/2024 style to 2024-03-14 style in all 9 matched rows. Same dates, new format.",
"3 emails changed only in upper/lower case (C-1002, C-1004, C-1008).",
"2 phones changed only in spaces (C-1006, C-1010).",
"C-1005 name changed from Elif Yilmaz to Elif Yılmaz, the only content change; it looks like an accent correction.",
"Columns: country_code added; country and fax removed."
],
"concerns": [
"C-1007 Greta Lind was removed and the context does not mention any row being dropped.",
"country was removed too, but the context only says fax was meant to go. The new country_code may or may not carry the same information."
],
"checks": [
"Confirm C-1007 Greta Lind was meant to be removed, or find out where their row went.",
"Spot-check that country_code matches the old country values, for example Sweden for C-1007's old row, and for a few other customers.",
"Check that the lowercased emails and the unspaced phones still work in the new system.",
"Confirm the C-1005 name with the accent is the correct spelling."
],
"change_note": "customers-new-system.csv has 9 rows against 10 in customers-old-crm.csv; C-1007 Greta Lind is missing. All 9 remaining rows changed, but 14 of the changed values are format only (dates, email case, phone spaces) and 1 is a name edit on C-1005. The fax column was dropped as planned. The country column was also removed and country_code added."
}
```
Class grades, matched by two columns
Input (input.json):
{
"task": "explain",
"old_name": "grades-week-6.csv",
"new_name": "grades-week-8.csv",
"context": "",
"facts": "{\"old_file\":\"grades-week-6.csv\",\"new_file\":\"grades-week-8.csv\",\"matched_by\":\"first_name + last_name\",\"sentence\":\"Compared 7 old rows with 8 new rows, matched by first_name + last_name: 1 row added, 0 removed, 7 changed, 0 unchanged. Columns: 1 changed type.\",\"counts\":{\"old_rows\":\"7\",\"new_rows\":\"8\",\"added\":\"1\",\"removed\":\"0\",\"changed\":\"7\",\"unchanged\":\"0\",\"changed_values\":\"9\",\"format_only_values\":\"0\",\"content_values\":\"9\"},\"columns\":{\"compared\":[\"class\",\"quiz_1\",\"quiz_2\",\"final\"],\"added\":[],\"removed\":[],\"type_changes\":[\"final: empty -> whole number\"],\"skipped\":[]},\"by_column\":[\"quiz_1: 1 row: up 22.2%\",\"quiz_2: 1 row: filled in\",\"final: 7 rows: filled in\"],\"changed_values_sample\":{\"shown\":9,\"of\":9,\"items\":[{\"key\":\"Sam / Rivera\",\"column\":\"final\",\"old\":\"\",\"new\":\"82\",\"change\":\"filled in\"},{\"key\":\"Leo / Chen\",\"column\":\"quiz_1\",\"old\":\"9\",\"new\":\"11\",\"change\":\"up 22.2%\"},{\"key\":\"Nora / Haddad\",\"column\":\"quiz_2\",\"old\":\"\",\"new\":\"12\",\"change\":\"filled in\"},{\"key\":\"Sam / Okoro\",\"column\":\"final\",\"old\":\"\",\"new\":\"74\",\"change\":\"filled in\"},{\"key\":\"Maya / Rivera\",\"column\":\"final\",\"old\":\"\",\"new\":\"95\",\"change\":\"filled in\"},{\"key\":\"Leo / Chen\",\"column\":\"final\",\"old\":\"\",\"new\":\"68\",\"change\":\"filled in\"},{\"key\":\"Nora / Haddad\",\"column\":\"final\",\"old\":\"\",\"new\":\"77\",\"change\":\"filled in\"},{\"key\":\"Ivan / Petrov\",\"column\":\"final\",\"old\":\"\",\"new\":\"70\",\"change\":\"filled in\"},{\"key\":\"Zoe / Martin\",\"column\":\"final\",\"old\":\"\",\"new\":\"91\",\"change\":\"filled in\"}]},\"added_rows_sample\":{\"shown\":1,\"of\":1,\"items\":[{\"key\":\"Aisha / Bello\",\"values\":\"first_name=Aisha; last_name=Bello; class=7A; quiz_1=15; quiz_2=16; final=80\"}]},\"removed_rows_sample\":{\"shown\":0,\"of\":0,\"items\":[]},\"settings\":[\"spaces at the start and end ignored\",\"upper/lower case counts\",\"1.50 and 1.5 count as the same number\"],\"notes\":[]}"
}Reply (job.output.output):
```json
{
"headline": "Week 8 fills in final scores for 7 students and adds Aisha / Bello; no rows were removed.",
"summary": "Compared 7 old rows with 8 new rows, matched by first_name + last_name. 1 row was added, 0 were removed and 7 changed, with 9 changed values in all. This is real content, not format: final was empty and is now filled in for 7 rows, quiz_2 was filled in for 1 row, and quiz_1 went up 22.2% for 1 row.",
"patterns": [
"final moved from empty to a whole number in 7 rows, for example Sam / Rivera 82 and Maya / Rivera 95.",
"Aisha / Bello is a new row: class 7A, quiz_1 15, quiz_2 16, final 80.",
"Nora / Haddad quiz_2 was filled in with 12, and Leo / Chen quiz_1 went from 9 to 11, up 22.2%."
],
"concerns": [
"Leo / Chen quiz_1 changed from a score that already existed, 9 to 11. It is the only edit to an old value, so it may be a correction or a typo."
],
"checks": [
"Confirm the Leo / Chen quiz_1 change from 9 to 11 was intended.",
"Confirm Aisha / Bello is a new student and that final 80 is correct for their row.",
"Spot-check a few final scores against the source, such as Zoe / Martin 91 and Ivan / Petrov 70."
],
"change_note": "grades-week-8.csv has 8 rows against 7 in grades-week-6.csv. Aisha / Bello was added and no rows were removed. All 7 matched rows changed: final scores were filled in, quiz_2 was filled in for 1 row, and quiz_1 went up 22.2% for 1 row."
}
```
Same list re-sorted: no differences
Input (input.json):
{
"task": "explain",
"old_name": "stock-by-id.csv",
"new_name": "stock-by-name.csv",
"context": "Did re-sorting the stock sheet in the spreadsheet change anything?",
"facts": "{\"old_file\":\"stock-by-id.csv\",\"new_file\":\"stock-by-name.csv\",\"matched_by\":\"id\",\"sentence\":\"No differences: all 6 rows match on id across 3 compared columns.\",\"counts\":{\"old_rows\":\"6\",\"new_rows\":\"6\",\"added\":\"0\",\"removed\":\"0\",\"changed\":\"0\",\"unchanged\":\"6\",\"changed_values\":\"0\",\"format_only_values\":\"0\",\"content_values\":\"0\"},\"columns\":{\"compared\":[\"item\",\"qty\",\"location\"],\"added\":[],\"removed\":[],\"type_changes\":[],\"skipped\":[]},\"by_column\":[],\"changed_values_sample\":{\"shown\":0,\"of\":0,\"items\":[]},\"added_rows_sample\":{\"shown\":0,\"of\":0,\"items\":[]},\"removed_rows_sample\":{\"shown\":0,\"of\":0,\"items\":[]},\"settings\":[\"spaces at the start and end ignored\",\"upper/lower case counts\",\"1.50 and 1.5 count as the same number\"],\"notes\":[\"The columns are in a different order. Values are compared by column name, so the order does not count as a change.\"]}"
}Reply (job.output.output):
```json
{
"headline": "No differences: all 6 rows match on id across 3 compared columns.",
"summary": "Both files have 6 rows, and every row was matched by id. All 6 are unchanged, with no added rows, no removed rows and no changed values. Re-sorting the sheet did not change the content. The only visible difference is that the columns are in a different order, which the page does not count as a change.",
"patterns": [],
"concerns": [],
"checks": [
"Spaces at the start and end of values were ignored, so a change that only added or removed such spaces would not show here.",
"The columns item, qty and location were compared by name, so a changed column order is not reported as a difference; check it if another tool reads this file by position.",
"1.50 and 1.5 count as the same number, so a quantity written in a different number format would not be flagged."
],
"change_note": "Compared stock-by-id.csv with stock-by-name.csv, matching rows by id. All 6 rows match across the item, qty and location columns, with 0 added, 0 removed and 0 changed. Re-sorting did not change the data. The columns are in a different order, which does not count as a change."
}
```
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://csv-compare.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://csv-compare.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"]// csv-compare.mjs -- Node 18+ (global fetch)
const BASE = "https://api.skillsafe.ai/v1/app-api";
let TOKEN = "paste-your-token-here"; // from https://csv-compare.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://csv-compare.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
}// CsvCompare.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 CsvCompare {
static final String BASE = "https://api.skillsafe.ai/v1/app-api";
static String token = "paste-your-token-here"; // from https://csv-compare.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://csv-compare.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://csv-compare.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://csv-compare.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":"csv-compare"}' | 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": "csv-compare"})["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: "csv-compare" })).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": "csv-compare"}, 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", "csv-compare"), 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: "csv-compare" })["token"])// a guest token (enough for /me and /estimate); a run needs your personal token from /tokens.html
$TOKEN = "";
$TOKEN = api("POST", "/guest", ["slug" => "csv-compare"])["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 = "csv-compare" }))!["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": "explain", "old_name": "prices-march.csv", "new_name": "prices-april.csv", "context": "", "facts": "{...}"}
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": "explain", "old_name": "prices-march.csv", "new_name": "prices-april.csv", "context": "", "facts": "{...}"}
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, old_name, new_name, context, facts}
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="csv-compare:explain:$(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: headline, summary, patterns, concerns, checks, change_note
echo "$J" | jq '.data | {charged_credits, truncated}' import hashlib, time
key = "csv-compare:" + 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"]) # {headline, summary, patterns, concerns, checks, change_note}
print(j["charged_credits"], j.get("truncated"), reply.get("headline"))import { createHash } from "node:crypto";
const key = `csv-compare:${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.headline);sum := sha256.Sum256(raw) // add "crypto/sha256", "encoding/hex", "time" to the imports
key := "csv-compare:" + 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 = "csv-compare:" + 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 = "csv-compare:#{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["headline"]].inspect$key = "csv-compare:" . $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["headline"], "\n";var digest = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(input.ToJsonString()));
var key = $"csv-compare:{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: csv-compare:explain:$(shasum -a 256 input.json | cut -c1-16):a1" --data @input.jsonrin = json.load(open("input.json")) # {"task": "explain", "old_name": "prices-march.csv", "new_name": "prices-april.csv", "context": "", "facts": "{...}"}
req = urllib.request.Request(BASE + "/run-stream", method="POST", data=json.dumps(rin).encode(),
headers={"Content-Type": "application/json", "Authorization": "Bearer " + TOKEN,
"Idempotency-Key": "csv-compare:explain:" + 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": `csv-compare:explain:${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", "csv-compare:explain:"+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", "csv-compare:explain:" + 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" => "csv-compare:explain:#{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: csv-compare:explain:" . 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", $"csv-compare:explain:{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);