tokencoup
Edition: International · 国内版 Language: ZH · EN
Get API keys
Gateway v0.4 · Reference

API Reference

One gateway, two modes. OpenAI-compatible request shape, Qianfan models behind it.

Pre-launch. https://api.tokencoup.com resolves at the Cloudflare edge but is not a live API: every request returns HTTP 503 with error.type=not_live (header X-Tokencoup-Status: pre-launch). The reference server runs locally at http://127.0.0.1:8081 (mock mode by default). Mode B (metered resale) has been cancelled (2026-11-13): it cannot be served compliantly until a real international-edition Qianfan key exists, and simulating one with a domestic key is a compliance violation (C2/S3). Requests to /intl/b now return 403 mode_B_not_allowed_on_intl. Everything below documents the contract that is already shipped and tested. v0.3 adds GET /v1/usage, GET /v1/models and buffered SSE. v0.4 meters token counts from the upstream usage field (JSON and the final SSE chunk), flags fallback estimates, and adds idempotency, atomic quota debits and UTC monthly billing periods. Prices remain placeholders — see the internal metering and billing design doc.

Overview

The tokencoup gateway is a thin, OpenAI-compatible proxy in front of Baidu Qianfan. It adds gateway-level authentication, rate limiting, usage metering and billing without rewriting your request body.

The edition and the mode are encoded in the URL path, not in headers. That makes the data-residency boundary explicit and prevents a domestic key from ever being used to serve an overseas request (C2/S3 guard).

EditionPath prefixModesUpstream baseData residency
International (intl)/intl/a/…, /intl/b/…A + Bhttps://api.baiduqianfan.ai/v1/Overseas — S1 target; actual data residency pending written confirmation from Baidu
Domestic (cn)/cn/a/…A onlyhttps://qianfan.baidubce.com/v2/Mainland China
Everything after the {edition}/{mode}/ prefix is appended to that edition's upstream base. Bases were verified against official Qianfan docs on 2026-11-12: https://api.baiduqianfan.ai/v1/ (intl) and https://qianfan.baidubce.com/v2/ (cn). The intl edition's overseas data-residency claim still requires written confirmation from Baidu; see the Cross-border page before relying on it.

Quickstart

  • Create a gateway API key (rf_…). Its plan sets your RPM and token quota.
  • Choose Mode A (bring your own Qianfan key) — available on both editions.
  • POST an OpenAI-style chat payload to /cn/a/….
cURL — Mode A
BASE=https://api.tokencoup.com

curl -s "$BASE/cn/a/v1/chat/completions" \
  -H "X-Gateway-Key: rf_YOUR_GATEWAY_KEY" \
  -H "Authorization: Bearer YOUR_QIANFAN_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "ernie-4.0-8k",
    "messages": [{"role": "user", "content": "Say hi in one sentence."}]
  }'
200 OK — upstream passthrough
{
  "id": "chatcmpl-…",
  "object": "chat.completion",
  "model": "ernie-4.0-8k",
  "choices": [{
    "index": 0,
    "message": {"role": "assistant", "content": "Hi there!"},
    "finish_reason": "stop"
  }],
  "usage": {"prompt_tokens": 12, "completion_tokens": 5, "total_tokens": 17}
}
Responses are passed through from Qianfan unchanged. Server-side audit metadata (edition, mode, key id, token count) is never returned in the body, and on the international edition it never contains prompt content.

Authentication

There are two distinct keys. Confusing them is the most common integration error.

HeaderApplies toValueHandling
X-Gateway-KeyAll requestsrf_… gateway API keySHA-256 hash stored in the gateway DB; linked to a plan and subscription
Authorization: Bearer …Mode A onlyYour own Qianfan keyNot stored; forwarded to the upstream
X-Provider-KeyMode A onlyAlternative to AuthorizationNot stored; forwarded to the upstream
Content-TypeAll requestsapplication/jsonRequired for JSON bodies
The reference server serves POST only. A missing, invalid or revoked X-Gateway-Key returns 401 gateway_auth_failed before any upstream call. The plaintext key is shown only once at creation.
Key edition is validated (C2/S3). A domestic Qianfan key on /intl/… — or an international key on /cn/… — is rejected with 403 key_edition_mismatch. Any key not explicitly registered in tokencoup's edition registry fails closed with 403 key_edition_unknown. Key prefixes are deliberately ignored: domestic and international Qianfan keys share the bce-v3/ALTAK- prefix, so a prefix cannot prove an edition.

Endpoints

POST is used for inference: the first two path segments select edition and mode, and the remainder is forwarded verbatim to the Qianfan upstream. GET covers two read-only endpoints: /v1/usage (local ledger) and /v1/models (upstream passthrough). GET calls are authenticated and rate-limited, but never consume tokens or incur billing. Video generation lives on separate single-segment prefixes — /vod/* (Baidu VOD v3) and /video/* (Qianfan native video, reusing your Qianfan key) — see *Video generation* below.

MethodPathModeMeaning
POST/cn/a/<qianfan-path>ABring-your-own-key relay — all editions
POST/intl/b/<qianfan-path>BCancelled 2026-11-13 — rejected with 403 (C2/S3)
GET/cn/{a|b}/v1/usageA/BMeasured local usage — no upstream call, no billing
GET/cn/{a|b}/v1/modelsA/Bverified public snapshot (17 models, 14 priced)
POST/vod/<vod-path>—Video generation (Baidu VOD v3) — async task, metered per task, not per token
POST/GET/video/<path>—Qianfan native video generation — reuses your Qianfan key, task-metered like /vod/*
Request body
{
  "model": "ernie-4.0-8k",
  "messages": [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Summarize this in two lines: …"}
  ],
  "temperature": 0.7,
  "stream": false
}
Model IDs above are illustrative (ERNIE family). Confirm the available IDs in the Qianfan console — tokencoup does not rewrite model. Treat any path below the prefix as Qianfan's own API surface (for example v1/chat/completions).

Usage (GET, local truth)

GET /cn/{a|b}/v1/usage returns values aggregated locally from the gateway's own subscriptions and usage_ledger tables. It makes no upstream call, is not metered and is not billed. Quota and RPM come from gateway/plans.py — the same source injected into the pricing page at build time.

Request
curl -s http://127.0.0.1:8081/cn/a/v1/usage \
  -H 'X-Gateway-Key: rf_...'
FieldMeaning
token_quota / rpm_limitPlan values from gateway/plans.py
token_used_billableMode B billable tokens (Mode B cancelled 2026-11-13; counter stays at 0)
token_remainingquota − token_used_billable
ledger_callsAll recorded calls (Mode A and Mode B)
ledger_tokensAll recorded tokens = measured + estimated
period_start / period_endUTC monthly billing period; quota resets at rollover
tokens_measuredTokens backed by the upstream usage field
tokens_estimatedTokens from the len(body)/4 fallback (not settlement-grade)
estimated_callsCalls whose token count is estimated
billed_amount_usdSum of billed_amount in the ledger
overage_usd_per_1k_tokensDerived from plans.TOKEN_PRICE_USD
v0.4: token counts come from the upstream usage field whenever present (JSON responses and the final SSE chunk). If the upstream omits it, the gateway falls back to len(body)/4 and records tokens_source=estimated; tokens_measured, tokens_estimated and estimated_calls expose the split. token_used_billable and ledger_tokens have different scopes: only billable Mode B calls increment the former. Neither is a final invoice — placeholder pricing and settlement require Baidu's written price (see the internal metering and billing design doc).

Model list (GET, passthrough)

GET /cn/{a|b}/v1/models is relayed to the Qianfan upstream under the same edition/key checks (C2 S3) as inference. Verified 2026-11-12: the public endpoint https://api.baiduqianfan.ai/v1/models returned HTTP 200 with 17 models, 14 carrying published per-token prices, with no authentication required. tokencoup does not rewrite that catalogue — the homepage model price table is a dated snapshot produced by site/fetch_models.py. Mock mode makes no network call and returns an empty list.

Request
curl -s http://127.0.0.1:8081/cn/a/v1/models \
  -H 'X-Gateway-Key: rf_...' -H 'Authorization: Bearer <your-qianfan-key>'
Compliance: all 14 models that declare datacenters report country_code: CN. This is upstream, first-party counterevidence to any claim that international traffic never enters mainland China. Directory prices are not a settlement commitment — confirm model IDs, prices and actual residency in the Qianfan console and in writing before launch. Models using a nested pricing schema (schema_version 2.x) are listed but not priced on the homepage.

Streaming (SSE)

Set stream: true in the request body. The response uses Content-Type: text/event-stream with OpenAI-style data: chunks terminated by data: [DONE]. v0.3 uses buffered passthrough: the upstream SSE body is read in full and written once. Chunk-by-chunk flushing is not implemented yet, so clients must not assume token-by-token latency. If the upstream emits a final chunk carrying usage, those tokens are metered as real values; otherwise the fallback is flagged estimated.

Request
curl -N http://127.0.0.1:8081/cn/a/v1/chat/completions \
  -H 'X-Gateway-Key: rf_...' -H 'Authorization: Bearer <your-qianfan-key>' \
  -H 'Content-Type: application/json' \
  -d '{"model":"ernie-4.0-8k","messages":[{"role":"user","content":"hi"}],"stream":true}'
Response shape (mock)
data: {"id":"mock-chunk-1","object":"chat.completion.chunk","mock":true,"choices":[...]}

data: [DONE]
Streaming bodies are never written to the audit log (GDPR: no prompt/response persistence). Mock mode emits three synthetic chunks plus [DONE] so SDK clients can be wired up without a provider key.

Modes: BYOK vs metered

Mode A — BYOKMode B — metered resale (cancelled)
Provider keyYou supply itCancelled (2026-11-13) — see §Mode B
BillingFlat subscription, no token markup—
Quota pre-checkNo—
Key edition checkYes (C2/S3 guard)—
Availabilityintl + cnRejected on all editions (403 mode_B_not_allowed_on_intl)
Data residencyFollows the edition—
C1. Domestic Qianfan terms prohibit resale / redistribution. Mode B is therefore disabled on the cn edition and returns 403 mode_B_not_allowed_on_cn. Only the international edition carries resale.

Errors

Errors are JSON objects with an error machine code; some also carry detail. Upstream Qianfan errors are passed through with their original status and body.

HTTPerrorWhenWhat to do
400edition_unknownPath lacks a valid {intl|cn}/{a|b} prefixUse a documented path
401gateway_auth_failedMissing, invalid or revoked X-Gateway-KeyRegenerate the gateway key
402quota_exceededMode B token quota exhaustedUpgrade plan or wait for the reset
403mode_B_not_allowed_on_cnMode B requested on the domestic editionUse /cn/a/… or switch to intl
403missing_provider_keyMode A without a provider keyAdd Authorization or X-Provider-Key
403key_edition_unknownProvider key is not registered in tokencoup's edition registry (prefix is not used)Register the key with an explicit domestic / international edition
403key_edition_mismatchProvider key edition ≠ serving edition (C2/S3)Match the key to the edition
429rate_limitedPlan RPM exceededBack off or upgrade
403mode_B_not_allowed_on_intlMode B cancelled (2026-11-13): domestic keys cannot serve international resale (C2/S3)Use Mode A with your own international Qianfan key
Error shape
{
  "error": "quota_exceeded",
  "detail": "subscription token quota exhausted; upgrade plan or wait for reset"
}

Rate limits

Limits are per gateway key, enforced with a 60-second sliding window (Redis when REDIS_URL is configured, in-memory fallback otherwise). The check happens before the upstream call, so a 429 never consumes tokens.

PlanRPMWindow
free6060 s
pro60060 s
scale6,00060 s

Recommended: exponential backoff with jitter on 429 and 5xx; never retry 401, 402 or 403 without fixing the request first.

Video generation (/vod)

Video generation is a separate category, not an edition of the text API. It lives on its own single-segment prefix /vod/* (Baidu VOD v3; see *Qianfan native video* below for the /video/* sibling), talks to a different upstream, and is metered per task, never per token. A single video task costs orders of magnitude more than a chat completion, so it must not share the token quota or the token ledger.

Pre-launch and fail-closed. No VOD credential is registered, so every /vod request returns 403 vod_key_unregistered today. This is deliberate: without a registered key the gateway refuses to forward to a metered upstream. The API subdomain still returns 503 not_live.

Paths

MethodPathMeaning
POST/PUT/vod/v3/aigc/text_to_videoText to video — creates an async task
POST/vod/v3/aigc/image_to_videoImage to video
POST/vod/v3/aigc/text_to_imageText to image
POST/vod/v3/aigc/image_to_imageImage to image
POST/vod/v3/aigc/video_cloneVideo clone
POST/vod/v3/aigc/video_extendVideo extend
POST/vod/v3/aigc/lip_syncLip sync
POST/vod/v3/aigc/create_effect_videoEffect video
POST/vod/v3/aigc/recommend/effectEffect recommendation
POST/vod/v3/aigc/imageImage generation
GET/vod/v3/tasks/{taskId}Poll task status — read-only, not metered
GET/vod/v3/aigc/effectList effects — read-only, not metered
GET/vod/v3/aigc/presets-voicesList preset voices — read-only

The v3 segment may be omitted (/vod/aigc/text_to_video is normalised). Only the endpoints on Baidu's published *API Key permission* list are accepted, matched by method and path-segment count; anything else returns 404 unknown_vod_endpoint. Arbitrary paths are never forwarded verbatim to the upstream.

Create a task

Request
curl -s -X POST 'https://api.tokencoup.com/vod/v3/aigc/text_to_video' \
  -H 'X-Gateway-Key: rf_...' \
  -H 'X-Vod-Key: <your Baidu VOD key>' \
  -H 'X-Request-Id: my-task-001' \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "P40",
    "modelP40TaskInput": {
      "duration": 5, "resolution": "540p", "aspectRatio": "16:9",
      "prompt": "a cat surfing a wave, cinematic"
    }
  }'

The upstream returns a taskId. Poll it with GET /vod/v3/tasks/{taskId} until the task completes. The request body is passed through unchanged apart from normalisation of the path.

Idempotency — checked before forwarding

Creating a task costs real money upstream, so replay protection runs before the forward, not after. Reusing the same X-Request-Id for the same gateway key returns the cached taskId with duplicate: true and makes zero new upstream calls. Omitting X-Request-Id makes the gateway generate one, but a generated value cannot be reused across retries.

Metering

FieldMeaning
unitAlways task
billable_units1 for one successfully created task; 0 otherwise
priced / billing_statusfalse / no_tariff — no VOD tariff exists yet
tokensAlways 0 — video is not metered in tokens
task_idUpstream task handle, when the response carries one
cost_driversmodel, duration, resolution, aspectRatio only
Video is recorded in a separate ledger (video_task_ledger), never in the token ledger, and it never decrements the token quota. If a 200 response carries no taskId, nothing is recorded (no_task_id) rather than inventing a handle. Because there is no VOD tariff, billable_units is recorded but no amount is produced — nothing here is an invoice line.

Keys and isolation

VOD keys are registered separately from Qianfan keys. The two registries are mutually exclusive: a key registered as a VOD key is rejected by the text endpoints, and a Qianfan key is rejected by /vod. String format cannot decide the category — Baidu's own VOD example key is bce-v3/ALTAK-…, identical in shape to a Qianfan key — so the registry is the only authority. An unregistered key returns 403 vod_key_unregistered.

Rate limits

Video has its own bucket (rlv:), separate from the text limit, because tasks are expensive and a retry storm would create dozens of billable tasks. The default is 2 requests per 60 s per gateway key.

Status and unverified edges

  • Upstream default is https://vod.bj.baidubce.com:443. Baidu documents HTTP and HTTPS and recommends HTTPS; the example in their API-Key page uses port 8301, which is not reachable from the public internet (verified: connection timed out), so the default is HTTPS/443. Override with TOKENCOUP_VOD_SCHEME / _HOST / _PORT.
  • The Bearer scheme is not yet confirmed on this host. Unauthenticated requests, the documented bce-v3/ALTAK- form and vod-v3/… all returned the same BceSignatureValidateException, which suggests the gateway on :443 expects AK/SK request signing rather than a Bearer key. Do not bill or promise this category until a real key returns 200.
  • The upstream response shape for task creation (the exact taskId field) is not documented on the API-Key page; the gateway accepts several common spellings and records nothing when none is present.

Qianfan native video (/video)

Qianfan also runs its own native video generation API under /beta/video/… on the domestic endpoint. The gateway exposes it on the single-segment prefix /video/* — a third category, separate from both the text API (/intl, /cn) and VOD (/vod). It reuses your Qianfan key: the same bce-v3/ALTAK-… Bearer credential and the same registry as the text API, so no separate registration is needed. It is still metered per task, never in tokens.

This path was verified against the live upstream on 2026-11-13 with a real domestic key: an invalid credential returns 401 invalid_iam_token (real authentication), while a valid key reaches the business layer and returns 400 invalid_video_generation_argument — a parameter error. Authentication on this path is confirmed, unlike the VOD host.

Paths

MethodPathMeaning
POST/video/generations/qianfan-videoCreate a task (text2video etc.)
GET/video/generations/qianfan-video/fireseries?task_id=…Poll task status — read-only, not metered
GET/video/generations/qianfan-video/m-series/listList tasks — read-only, not metered

The path after /video/ must match one of the three documented endpoints exactly (method and segments both checked); anything else returns 404 unknown_qf_video_endpoint. Query strings (?task_id=…) are passed through verbatim.

Create a task

Request
curl -s -X POST 'https://api.tokencoup.com/video/generations/qianfan-video' \
  -H 'X-Gateway-Key: rf_...' \
  -H 'Authorization: Bearer <your Qianfan key>' \
  -H 'X-Request-Id: my-video-001' \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "VQ3-Pro", "type": "text2video",
    "prompt": "a cat surfing a wave, cinematic"
  }'

The upstream returns a task_id together with a usage block (duration, resolution, total_tokens). Poll the status with the fireseries endpoint until the task completes. total_tokens here is the video-token accounting of the upstream — the gateway never adds it to the token ledger or the token quota; it is stored as task metadata only.

Metering

FieldMeaning
unitAlways task
billable_units1 for one successfully created task; 0 otherwise
priced / billing_statusfalse / no_tariff — no published tariff yet, no amount produced
tokensAlways 0 — video is not metered in tokens
task_idUpstream task handle
upstream_usageUpstream-provided duration / resolution / total_tokens, recorded as metadata

Official tariff (updated 2026-10-14, reference only)

Qianfan video is billed in credits, 1 credit = 1 RMB. The table below is transcribed verbatim from the official credit-deduction table (qianfan-multimodal doc “视频生成模型价格”, page updated 2026-10-14). Note: the gateway still does not bill — the tariff is public, but the duration × resolution × model matching required for pricing has not been wired into billing code, so priced remains false.

SeriesBilling modePrice (RMB)
VQ4per second × resolution540p 0.28125/s; 720p 0.59375/s; 1080p 0.75/s; 2K 1.1875/s; 4K 2.4375/s
VQ3-Proper clip (1–16 s)1080p 0.9375; 720p 0.78125; 540p 0.3125
VQ3-Turboper clip (1–16 s)1080p 0.4375; 720p 0.3750; 540p 0.2500
VQ2 (text/image/first-last-frame)per duration × resolutione.g. VQ2 text-to-video 540p 1s 0.3125 / 10s 0.875; 1080p 1s 0.625 / 10s 3.4375
VQ2-Pro (reference-video)per-second incremental540p 1st s 0.625 + 0.15625 each additional s; 720p 1st s 0.9375 + 0.15625/s; 1080p 1st s 2.65625 + 0.3125/s
VQ2 audio-video direct outputsurcharge+0.46875 credits per task on image-to-video / reference-video tasks

The full three-dimensional table (every VQ2 model × duration tier × three resolutions) is in the official page; only structure and representative rows are reproduced here — not the complete tariff. Source: cloud.baidu.com/doc/qianfan-multimodal/s/nmo74mg17 (public web page, crawled 2026-11-13).

Keys and isolation

The key must be registered in the Qianfan registry with edition domestic — the beta video endpoints live on qianfan.baidubce.com and the international edition has not been verified on this path, so international keys are rejected with 403 qf_video_key_edition (fail-closed). A key registered in the VOD registry is rejected with 403 qf_video_key_unregistered, completing the two-way isolation with /vod: string format cannot decide the category, only the registry can.

Rate limits

Qianfan video has its own bucket (rlq:), separate from both the text bucket (rl:) and the VOD bucket (rlv:). Default is 2 requests per 60 s per gateway key; override with TOKENCOUP_QF_VIDEO_RPM / _RPM_WINDOW.

Status

Authentication is verified against the live upstream (2026-11-13). End-to-end creation of a real task has not been exercised with a billable payload yet — the request body schema (model, type, model_parameters) follows the official documentation and the no_tariff status still applies until a tariff is published. Idempotent replay protection (same X-Request-Id returns the cached task_id, zero new upstream calls) works exactly as on /vod.

Data residency (domestic edition)

The domestic edition serves Mode A only. Its upstream is the domestic Qianfan endpoint, log_prompt is true for domestic compliance, and requests are never routed through the Cloudflare edge — keeping the S2 closed path intact.

Resale (Mode B) is unavailable on this edition under the domestic Qianfan terms — and was cancelled globally on 2026-11-13. Mode A (bring your own key) is the only gateway mode.

Machine-readable spec

An OpenAPI 3.1 description of the three path families is published at openapi.json. Import it into Postman, Insomnia or an SDK generator to scaffold a client.

Point any OpenAI-compatible SDK's base_url at https://api.tokencoup.com/cn/a/v1 and set X-Gateway-Key as a default header. The gateway does not rewrite payloads, so standard chat-completion helpers work as-is.

FAQ

Do I need my own Qianfan account?

Mode A: yes. Mode B: cancelled (2026-11-13) — bring your own international Qianfan key.

Is my prompt stored?

On the international edition, no (log_prompt=false, collect_logs=false). On the domestic edition, prompt logging is enabled for domestic compliance.

Can I use a domestic Qianfan key on the international endpoint?

No. That is the permanently blocked C2/S3 path; the gateway returns 403 key_edition_mismatch.

When am I charged?

No — /intl/a rejects domestic keys with 403 key_edition_mismatch (C2/S3 guard), and /intl/b is cancelled entirely. This is enforced in code, not policy.

Is streaming supported?

Yes, since v0.3: stream: true returns buffered SSE. v0.4 also reads a final usage chunk when the upstream provides one. Chunk-by-chunk flushing is not implemented.