Skip to content
Sparecycle

OpenAI-compatible API

Point an OpenAI SDK at https://sparecycle.tech/v1 (or https://sparecycle.tech/api/v1) and use a Sparecycle API key. Two models only: qwen2.5-1.5b for chat and sd15 for images (prices, limits and live capacity on Models). Every job runs on two nodes with different owner wallets and you get an answer only when both agree; if they don't, you get an error that says nothing was charged, never a made-up answer. Today every node is project-run, so both wallets belong to the project.

Async by default: create, then poll

A create call answers 202 right away with the usual OpenAI object and an empty choices (chat) or data (images), plus a sparecycle block: job_id, status, price_wei, the poll path and receipt_url. Poll that path until choices / data is filled. For chat, the SDKs' chat.completions.retrieve(id) is the poll.

sparecycle.receipt_url is the job's receipt (GET /api/v1/jobs/<job_id>/receipt, read with the same key). It answers 409 until the two results are compared, then a provisional receipt with both nodes' signed results, sealed once the epoch's charge is on-chain. Check it against the chain on the Jobs page or with src/lib/job-receipt.ts. See Billing.

If no two nodes with different owners can take the model right now, neither online nor through the project's GPU pool, a create answers 503 no_node_pair at once: nothing is queued, held or charged. GET /v1/catalog (no key) shows each model's live capacity.

To wait instead, send Prefer: wait=<seconds> (RFC 7240) on a create or poll: the server holds the request until the job has a verdict or the time is up, and answers 200 with the finished object, or the 202 object if it is still running. The wait is capped at 25 seconds on this server (API_MAX_WAIT_SECONDS). The cap must stay below the hosting platform's request timeout, which has not been confirmed yet, so it may change. A9: default, not yet confirmed

Nothing is streamed: stream: true is refused with 400 streaming_not_supported, because no part of an answer exists before two nodes agree. A11: default, not yet confirmed

Retries and Idempotency-Key

The OpenAI SDKs retry some failures on their own (408, 409, 429, 5xx and connection errors, twice by default). A retried create could queue and pay for a second job. Two rules keep that from happening:

  • Once a job is queued, the create call never answers with a retryable status.
  • Send an Idempotency-Key header (1 to 255 visible characters, unique per job). The same key with the same body within 6 hours returns the first job (with Idempotent-Replayed: true); the same key with another body is refused with 400 idempotency_key_reused. A10: default, not yet confirmed

Send an Idempotency-Key with every create, or set maxRetries: 0 (JS) / max_retries=0 (Python) for create calls.

JavaScript / TypeScript (official SDK)

Tested with openai@7.64.0.

chat.mjs
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://sparecycle.tech/v1", apiKey: process.env.SPARECYCLE_API_KEY });

// 202: choices is [] until two nodes agree. The Idempotency-Key makes the SDK's own retries safe.
const created = await client.chat.completions.create(
  { model: "qwen2.5-1.5b", messages: [{ role: "user", content: "Name three colours." }], max_tokens: 64 },
  { headers: { "Idempotency-Key": crypto.randomUUID() } },
);
console.log(created.id, created.sparecycle.status, created.sparecycle.price_wei);

for (;;) {
  try {
    const done = await client.chat.completions.retrieve(created.id, { headers: { Prefer: "wait=20" } });
    if (done.choices.length) {
      console.log(done.choices[0].message.content);
      break;
    }
  } catch (e) {
    // 422 = the nodes did not agree, no verdict in time, or a rejected image: nothing was charged.
    if (e instanceof OpenAI.APIError && e.status === 422) {
      console.log("not charged:", e.code);
      break;
    }
    throw e;
  }
}
images.mjs
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://sparecycle.tech/v1", apiKey: process.env.SPARECYCLE_API_KEY });

// steps, guidance, negative_prompt and seed are Sparecycle fields: plain extra body fields in JS.
const created = await client.images.generate(
  { model: "sd15", prompt: "a lighthouse at dusk, oil painting", size: "512x512", steps: 20 },
  { headers: { "Idempotency-Key": crypto.randomUUID() } },
);

// The OpenAI SDKs have no call to poll an image: use the generic GET.
let image;
do {
  image = await client.get(created.sparecycle.poll.replace(/^\/v1/, ""), { headers: { Prefer: "wait=20" } });
} while (!image.data.length);
await import("node:fs").then((fs) => fs.writeFileSync("out.png", Buffer.from(image.data[0].b64_json, "base64")));

In TypeScript, sparecycle is not in the SDK's types: read it as (created as any).sparecycle, and pass the extra image fields in an object typed as any.

Python (official SDK)

Tested with openai==3.59.0.

chat.py
import os, time, uuid
from openai import OpenAI, APIStatusError

client = OpenAI(base_url="https://sparecycle.tech/v1", api_key=os.environ["SPARECYCLE_API_KEY"])

created = client.chat.completions.create(
    model="qwen2.5-1.5b",
    messages=[{"role": "user", "content": "Name three colours."}],
    max_tokens=64,
    extra_headers={"Idempotency-Key": str(uuid.uuid4())},
)
print(created.id, created.model_extra["sparecycle"]["status"])

while True:
    try:
        done = client.chat.completions.retrieve(created.id, extra_headers={"Prefer": "wait=20"})
    except APIStatusError as e:
        if e.status_code == 422:  # not charged: results did not match, expired or rejected
            print("not charged:", e.body)
            break
        raise
    if done.choices:
        print(done.choices[0].message.content)
        break
    time.sleep(2)
images.py
import base64, os, uuid
from openai import OpenAI

client = OpenAI(base_url="https://sparecycle.tech/v1", api_key=os.environ["SPARECYCLE_API_KEY"])

created = client.images.generate(
    model="sd15",
    prompt="a lighthouse at dusk, oil painting",
    size="512x512",
    extra_body={"steps": 20, "negative_prompt": "blurry"},
    extra_headers={"Idempotency-Key": str(uuid.uuid4())},
)
poll = created.model_extra["sparecycle"]["poll"].removeprefix("/v1")
while True:
    image = client.get(poll, cast_to=object, options={"headers": {"Prefer": "wait=20"}})
    if image["data"]:
        break
with open("out.png", "wb") as f:
    f.write(base64.b64decode(image["data"][0]["b64_json"]))

curl

curl
curl -s https://sparecycle.tech/v1/chat/completions \
  -H "Authorization: Bearer $SPARECYCLE_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{"model":"qwen2.5-1.5b","messages":[{"role":"user","content":"Name three colours."}],"max_tokens":64}'
# 202 {"id":"chatcmpl-0x…","object":"chat.completion","choices":[],"sparecycle":{"job_id":"0x…","status":"queued",…}}

curl -s https://sparecycle.tech/v1/chat/completions/chatcmpl-0x… \
  -H "Authorization: Bearer $SPARECYCLE_API_KEY" -H "Prefer: wait=20"

curl -s https://sparecycle.tech/v1/models -H "Authorization: Bearer $SPARECYCLE_API_KEY"

What each model accepts

Chat: qwen2.5-1.5bAccepted
messagesat most one system message (up to 500 characters), then exactly one user message (1 to 2000 characters); string content only, no multi-turn
max_tokens16 to 512; default 256 A7: default, not yet confirmed (max_completion_tokens works too)
temperature, top_paccepted and ignored: decoding is always greedy on the nodes, and every answer says sparecycle.decoding: "greedy"
refused (400)stream: true, n other than 1, tools / functions, response_format other than text, logprobs, seed, content parts
Images: sd15Accepted
prompt1 to 500 characters
size"<width>x<height>", each side 256 to 512 in steps of 64; default 512x512
response_formatb64_json (default) A8: default, not yet confirmed or url: the authenticated /api/v1/jobs/<id>/result, which needs the same key (b64_json when left out)
Sparecycle fields (extra_body)negative_prompt up to 300 characters, steps 10 to 30 (default 20), guidance 1 to 12 (default 7), seed 0 to 4294967295 (chosen by the scheduler when left out)
refused (400)n other than 1, quality, style, background, stream: true, an output_format other than png

Any other model name answers 404 model_not_found. GET /v1/models lists exactly the two models (with a key); GET /v1/catalog lists them without a key, with the price per unit, the limits and live capacity. The price is the same as on Submit a job: work units times the price per unit, in sparecycle.price_wei.

What an answer contains, and what it doesn't

  • No usage object: the scheduler does not count tokens, and no number is made up. sparecycle.work_units is given instead (the unit the price is computed from).
  • finish_reason is always "stop": the nodes do not report why generation stopped, and sparecycle.finish_reason_reported: false says so.
  • Your prompt is never echoed back. Results are returned only to the key that submitted the job, or to your wallet's sign-in.
  • Models have no created date in /v1/models: no release date is published for them here.

Errors

Errors use the OpenAI shape { "error": { "message", "type", "param", "code" } }. Every answer carries Cache-Control: private, no-store.

HTTPcodetypeWhen
401invalid_api_keyauthentication_errormissing, unknown, disabled or deleted key
403forbiddenpermission_errorthe job was submitted by another key or wallet
404model_not_foundinvalid_request_errora model other than qwen2.5-1.5b or sd15
400invalid_requestinvalid_request_errora parameter outside the limits above; param names it
400streaming_not_supportedinvalid_request_errorstream: true
400idempotency_key_reusedinvalid_request_errorthe Idempotency-Key was used with another body
402insufficient_balancebilling_erroravailable balance below the price
429key_daily_cap_reachedrate_limit_errorthe key's cap for today (UTC) is used up; answered with x-should-retry: false
429rate_limitedrate_limit_errormore paid jobs per hour from one wallet than allowed
503queue_fullserver_errorthe job queue is full; nothing was queued
503no_node_pairserver_errorno two nodes with different owners can take the model now, neither online nor through the GPU pool; nothing was queued, held or charged. Answered with x-should-retry: false, and Retry-After when the pool is waiting to try again
422results_did_not_matchnot_chargedthe two nodes' results differ (poll only)
422job_expirednot_chargedno verdict within the job time limit, or the key was disabled before the job ran (poll only)
422content_rejectednot_chargeda node's safety checker rejected the image (poll only)

The three 422 not_charged outcomes come only from a poll (or a create with Prefer: wait), never as a fake completion. 422 is not in the SDKs' retry list, so a client does not resubmit on its own. Nothing is charged for these jobs; their sparecycle block still carries receipt_url, whose receipt shows the job as not charged.