$ cheapinference --api-reference --read-the-source-of-truth
A single Anthropic-compatible Messages endpoint carries everything: text, images, tools, streaming, conversations. Point any existing client at us by swapping two lines — every behavior below is what the gateway actually does, verified against the running code.
POST /v1/messages · SSE streaming
✓x-api-key or Bearer auth
✓Advertised ≡ billed: −50%, always
Need the full internals? Every service surface (worker rail, control plane, portal,
ops console, shared wire canons) lives in the repo-wide reference:
docs/API.md — this page's server-sent source.
The API lives at https://api.cheapinference.net. Authenticate every request
with your key (sk-cfp-…, issued in your
dashboard) using either header:
$ curl https://api.cheapinference.net/v1/messages \
-H "x-api-key: sk-cfp-YOURKEY" # or:
-H "Authorization: Bearer sk-cfp-YOURKEY" \
-H "content-type: application/json" \
-d @request.json
Keys activate instantly after your first credit top-up. Keys never appear in logs and you can rotate yours anytime from the dashboard.
| Method & path | What it does |
|---|---|
POST /v1/messages |
Create a message: text, images, tools, conversation resume — streaming (SSE)
or single JSON. Body: the Anthropic Messages request shape
(/v1/messages?beta=true is accepted identically). |
GET /healthz |
Liveness snapshot. JSON: { ok:true, service:"gateway",
workers:[…], inflight:N, bindings:N, held:N }. No auth needed;
available to feed your uptime monitors. |
Anything else answers
404 not_found_error. That's the entire surface — no hidden verbs.
POST /v1/messages| Field | Type / rule |
|---|---|
model optional |
Family alias sonnet · opus · fable
(resolved to the current generation, so prices can't drift under you),
or an exact pinned name like claude-sonnet-5-5.
Omitted → claude-sonnet-5-5. A well-formed name we don't serve yet gets
an honest 400 naming the supported set — we only ever bill models
whose exact rates we know. See live pricing. |
messages required |
Non-empty array of { role, content } — roles are free strings
(conventionally alternate user/assistant,
starting user). content is either a plain string or an
array of typed parts (see below). |
stream optional |
true → respond over Server-Sent Events; omit/false →
single JSON message. Default false. |
max_tokens optional |
Integer ≥ 1 bounding this turn's output tokens. Declaring more than the platform ceiling (64,000 today) is refused loudly with both numbers — never silently clamped. Omitting serves the turn at the ceiling. |
system optional |
A string, or an array of {type:"text", text} parts (joined with newlines).
Passed through to Claude as additional system guidance for the turn. |
tools optional |
Array of { name, description?, input_schema? }. Names match
^[a-zA-Z0-9_-]{1,128}$ and must be unique. Only tools declared here
get parsed out of replies as real calls — anything else renders as literal text. |
tool_choice optional |
{"type":"auto"|"any"|"tool","name?"} —
with "type":"tool", name is required
and must exist in tools. |
metadata.conversation_id optional |
String matching ^[A-Za-z0-9][A-Za-z0-9_-]{5,63}$. This is a
compatibility and routing hint, not a promise of server-side history storage.
Send your full message history on every turn rather than relying on this id to restore
earlier context. See context handling. |
messages[].content| Part type | Shape |
|---|---|
text |
{ type:"text", text:"…" } |
image |
{ type:"image", source } with
source.type:"base64"
(source.media_type ∈ image/png · jpeg · webp · gif,
strict single-line base64 in source.data)
or source.type:"url" (source.url, http(s)). See
image rules & limits. |
tool_use |
{ type:"tool_use", id:"…", name:"…", input?:{…} } — replay our
assistant turn back to continue an agent loop. Names obey the same
^[a-zA-Z0-9_-]{1,128}$; input passes through untouched. |
tool_result |
{ type:"tool_result", tool_use_id:"…", content:"…"|[text parts],
is_error?:true } — your answer to a call. Text-only today: inline images
aren't supported inside results yet (send them as parts of the user message). |
| anything else | Unknown future part types never 400: they validate untouched and travel visibly
as [part:<type>] — today's requests survive tomorrow's API
additions byte-for-byte. |
Errors here are 400 invalid_request_error with precise JSON-path
messages (messages[2].content[0].missing string \`text\`) so typos take
seconds, not minutes, to find.
| Mode | How to use it | Server-side semantics |
|---|---|---|
| Full history (recommended) | Omit metadata.conversation_id. Send the full transcript each turn —
standard client behavior. |
The entire messages array becomes one role-tagged transcript
([user]\n…
\n\n[assistant]\n…); all images in the transcript ride along, in order.
Long repeated transcripts benefit from automatic prefix caching upstream. |
| Compatibility id | You may include a valid metadata.conversation_id, but should still send
the full message history. Do not treat the id as server-side conversation storage. |
The id can act as an internal routing hint; it is not a history-recovery guarantee. To avoid missing context, omit it or always send full history rather than only the newest user message. |
Provide every piece of context the current turn needs. Tools, images and streaming use the same request shape in either case.
{
"id": "msg_gw_m8xq2z1a4kp", // gateway-minted ids, distinct namespace
"type": "message",
"role": "assistant",
"model": "sonnet", // echoed verbatim from your request
"content": [ { "type": "text",
"text": "Hello! How can I help?" } ],
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": { "input_tokens": 19, "output_tokens": 8,
"cache_read_input_tokens": 1188, // present when reported upstream
"cache_creation_input_tokens": 452 }
}{ …
"content": [
{ "type": "text", "text": "Checking the weather…" },
{ "type": "tool_use", "id": "toolu_gw_9ab41cdz",
"name": "get_weather",
"input": { "city": "Oslo" } } ],
"stop_reason": "tool_use", // derived purely from parsed content blocks
… }Your turn ends with stop_reason:"end_turn", or
"tool_use" when at least one valid call parsed out. Include a
tool_result part in the full message history of your next request to
continue the loop; do not rely on a conversation_id to restore prior turns.
event: message_start
data: {"type":"message_start","message":{"id":"msg_gw_…","model":"sonnet","role":"assistant",…}}
event: content_block_start # an empty text block opens eagerly —
data: {"index":0,"content_block":{"type":"text"}} # first deltas arrive immediately
event: content_block_delta
data: {"index":0,"delta":{"type":"text_delta","text":"Hello!"}}
event: content_block_stop
data: {"index":0}
event: message_delta # final truth: stop_reason + full usage
data: {"delta":{"stop_reason":"end_turn"},"usage":{"input_tokens":19,"output_tokens":8}}
event: message_stop
content_block_start (type tool_use +
id/name) → content_block_delta
(input_json_delta carrying the complete argument JSON in one frame —
concatenate, parse once) → content_block_stop. Any trailing text
afterwards opens a fresh text block at the next index.stop_reason comes from the very same
content-block verdict that built the JSON path — the two transports can never disagree.error event (
{"type":"error","error":{"type":"api_error"|"overloaded_error",
"message":"upstream: "}} ) plus message_stop close the
stream — nothing vanishes beneath an error, and anything you received and we actually
delivered is all you're billed for.| Rule | Behavior |
|---|---|
| Sources | base64 (strict alphabet A-Za-z0-9+/ + optional
= padding, single line, no whitespace) or
url — URLs are fetched once at admission, before dispatch, and ride
onward as bytes; retries never re-fetch. |
| Formats | image/png · image/jpeg · image/webp · image/gif |
| Truth wins | Every payload is magic-byte-sniffed: declare jpeg, ship PNG bytes →
honest 400 naming both values. We never silently relabel a broken
client. URL sources carry no trusted label at all — their bytes decide. |
| Limits (defaults) | ≤ 8 images per request · ≤ 5 MiB decoded binary per image (wire/base64 inflation never counts against it) · 10 s fetch deadline per URL · counts toward the 32 MiB total-body ceiling. |
| Placement | Include every image the current turn needs in this request; do not rely on images
from earlier requests remaining available. Inside tool_result parts images
aren't supported yet — attach them to the user message instead. |
Any violation refuses at admission with an exact, indexed message
(images[1] decodes to 5,342,208 bytes, over the per-image cap…) —
a refused request charges nothing.
Every error is {"type":"error",
"error":{"type":".
| Status | Type | When |
|---|---|---|
| 400 | invalid_request_error |
Malformed JSON; field violations with exact paths; unsupported
model names; max_tokens above the ceiling (both numbers
named); image rule violations (indexed, both knobs named);
bad conversation_id; tool_choice.name not among declared
tools. |
| 401 | authentication_error |
Missing or unknown API key. |
| 403 | authentication_error |
Key expired (renew in the portal) or prepaid credit exhausted (top up to continue). One admitted turn may overshoot a near-zero balance by at most its own final cost — visible honestly, never estimated. |
| 429 | rate_limit_error |
Capacity & fairness signals. Always paired with an integer
Retry-After seconds, computed from live fleet state — never invented.
See the pacing table below. |
| 502 | api_error |
Upstream failure mid-turn (non-streaming form; streams emit the SSE
error event instead). Nothing that wasn't genuinely delivered is
billed. |
| 503 | overloaded_error |
Upstream queue full / acquire timeout while dispatching; also the fail-closed answer during brief billing-store hiccups. Retry shortly. |
| 500 | api_error |
Internal gateway error — logged loudly on our side. |
We serve real accounts paced like real humans — that cadence, not token buckets, is the
product. Under load your request may be politely held for up to ~60 s
before even the first byte; if no serving slot appears in time you get a
429 with an honest Retry-After. Official SDKs honor
Retry-After natively — point one at us and retry handling is already
correct.
| Reason | Meaning | Retry-After |
|---|---|---|
key_concurrency |
This key already has its cap of simultaneous turns riding (in-flight + queued; 2 today). Complete or await current turns. | ~5 s |
daily_budget |
Optional per-key daily spend ceiling hit — prepaid balance untouched; spend resumes automatically at UTC midnight. | seconds to UTC midnight |
queue_full |
Momentary global queue depth at capacity. | ~10 s |
hold_expired |
Your request waited its full hold window without a waking serving slot. | computed from fleet ETA |
seat_unresolved |
No serving account bound to you yet — provisioning still completing right after sign-up / top-up. | poll-honest, ≥ 5 s |
Rejections never charge anything: billing happens exclusively after a turn truly served, from upstream-reported usage numbers.
| Limit | Default | Notes |
|---|---|---|
| Request body size | 32 MiB | Pre-parse transport cap; oversize refusal names both numbers
(CFP_MAX_BODY_BYTES). |
| Output tokens per turn | ceiling 64,000 | Declared max_tokens above it → honest 400; omitted → served at it.
Enforced per-model downstream, worst-case turn cost structurally bounded. |
| Images | ≤ 8/request · ≤ 5 MiB each · 10 s/URL fetch | Caps counted in decoded binary bytes. |
| Conversation id | ^[A-Za-z0-9][A-Za-z0-9_-]{5,63}$ |
Compatibility/routing hint only; not a server-side history-storage guarantee. |
| Turn watchdog | 630 s | Fence-sitting-tail safety net: turns that somehow stall are ended honestly and billed only for what was genuinely delivered. |
| Hold window | 60 s | Time a request waits for an awake serving slot before its honest 429. |
| Tool names | ^[a-zA-Z0-9_-]{1,128}$, unique |
Bounds both halves of the tool protocol — declarations and replayed calls. |
Live rate cards: see pricing — every price on this site renders from the same shared rate cards the gateway bills with, re-verified automatically at boot.
base_url and
api_key in whatever you run today. Everything else stays put.It's compatible-with, not pass-through-to. Requests speak the Anthropic Messages shape end to end, and are served by pooled, carefully-run real Claude accounts behind the gateway — which is why every token bills at 50% below the official API price. Client-visible behavior documented on this page IS the contract; anything not written here isn't promised.
Model names resolve from current generations with stable prices; request bodies are
validated generously with helpful errors; the retry signal is
Retry-After-based pacing rather than token-per-minute throttles; and idle
capacity occasionally holds requests briefly instead of rejecting instantly — designed
so stock SDK retry logic handles it without configuration. Every listed limit, error
shape, and event above mirrors deployed gateway behavior.
msg_gw_…, toolu_gw_…?Responses mint gateway-namespaced ids by design: unambiguous against upstream id namespaces, collision-free across tool-call blocks, and the single correlation key we use to join your request id, billing ledger row, and delivery telemetry end-to-end. Quote them to support and you quote exactly the turn your bill came from.
Email [email protected] with
your request id (msg_gw_…) — every turn is correlated end to end on our
side and the exact usage numbers your bill came from stay auditable forever.
Create an account, add ERC20-USDT credit, and point your existing client at the URL above — that's the whole integration.
Create an account