API Reference
One gateway, two modes. OpenAI-compatible request shape, Qianfan models behind it.
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).
| Edition | Path prefix | Modes | Upstream base | Data residency |
|---|---|---|---|---|
International (intl) | /intl/a/…, /intl/b/… | A + B | https://api.baiduqianfan.ai/v1/ | Overseas — S1 target; actual data residency pending written confirmation from Baidu |
Domestic (cn) | /cn/a/… | A only | https://qianfan.baidubce.com/v2/ | Mainland China |
{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/….
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."}]
}'{
"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}
}Authentication
There are two distinct keys. Confusing them is the most common integration error.
| Header | Applies to | Value | Handling |
|---|---|---|---|
X-Gateway-Key | All requests | rf_… gateway API key | SHA-256 hash stored in the gateway DB; linked to a plan and subscription |
Authorization: Bearer … | Mode A only | Your own Qianfan key | Not stored; forwarded to the upstream |
X-Provider-Key | Mode A only | Alternative to Authorization | Not stored; forwarded to the upstream |
Content-Type | All requests | application/json | Required for JSON bodies |
X-Gateway-Key returns 401 gateway_auth_failed before any upstream call. The plaintext key is shown only once at creation./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.
| Method | Path | Mode | Meaning |
|---|---|---|---|
| POST | /cn/a/<qianfan-path> | A | Bring-your-own-key relay — all editions |
| POST | /intl/b/<qianfan-path> | B | Cancelled 2026-11-13 — rejected with 403 (C2/S3) |
| GET | /cn/{a|b}/v1/usage | A/B | Measured local usage — no upstream call, no billing |
| GET | /cn/{a|b}/v1/models | A/B | verified 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/* |
{
"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. 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.
curl -s http://127.0.0.1:8081/cn/a/v1/usage \
-H 'X-Gateway-Key: rf_...'| Field | Meaning |
|---|---|
token_quota / rpm_limit | Plan values from gateway/plans.py |
token_used_billable | Mode B billable tokens (Mode B cancelled 2026-11-13; counter stays at 0) |
token_remaining | quota − token_used_billable |
ledger_calls | All recorded calls (Mode A and Mode B) |
ledger_tokens | All recorded tokens = measured + estimated |
period_start / period_end | UTC monthly billing period; quota resets at rollover |
tokens_measured | Tokens backed by the upstream usage field |
tokens_estimated | Tokens from the len(body)/4 fallback (not settlement-grade) |
estimated_calls | Calls whose token count is estimated |
billed_amount_usd | Sum of billed_amount in the ledger |
overage_usd_per_1k_tokens | Derived from plans.TOKEN_PRICE_USD |
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.
curl -s http://127.0.0.1:8081/cn/a/v1/models \
-H 'X-Gateway-Key: rf_...' -H 'Authorization: Bearer <your-qianfan-key>'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.
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}'data: {"id":"mock-chunk-1","object":"chat.completion.chunk","mock":true,"choices":[...]}
data: [DONE][DONE] so SDK clients can be wired up without a provider key.Modes: BYOK vs metered
| Mode A — BYOK | Mode B — metered resale (cancelled) | |
|---|---|---|
| Provider key | You supply it | Cancelled (2026-11-13) — see §Mode B |
| Billing | Flat subscription, no token markup | — |
| Quota pre-check | No | — |
| Key edition check | Yes (C2/S3 guard) | — |
| Availability | intl + cn | Rejected on all editions (403 mode_B_not_allowed_on_intl) |
| Data residency | Follows the edition | — |
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.
| HTTP | error | When | What to do |
|---|---|---|---|
| 400 | edition_unknown | Path lacks a valid {intl|cn}/{a|b} prefix | Use a documented path |
| 401 | gateway_auth_failed | Missing, invalid or revoked X-Gateway-Key | Regenerate the gateway key |
| 402 | quota_exceeded | Mode B token quota exhausted | Upgrade plan or wait for the reset |
| 403 | mode_B_not_allowed_on_cn | Mode B requested on the domestic edition | Use /cn/a/… or switch to intl |
| 403 | missing_provider_key | Mode A without a provider key | Add Authorization or X-Provider-Key |
| 403 | key_edition_unknown | Provider key is not registered in tokencoup's edition registry (prefix is not used) | Register the key with an explicit domestic / international edition |
| 403 | key_edition_mismatch | Provider key edition ≠ serving edition (C2/S3) | Match the key to the edition |
| 429 | rate_limited | Plan RPM exceeded | Back off or upgrade |
| 403 | mode_B_not_allowed_on_intl | Mode B cancelled (2026-11-13): domestic keys cannot serve international resale (C2/S3) | Use Mode A with your own international Qianfan key |
{
"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.
| Plan | RPM | Window |
|---|---|---|
free | 60 | 60 s |
pro | 600 | 60 s |
scale | 6,000 | 60 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.
/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
| Method | Path | Meaning |
|---|---|---|
| POST/PUT | /vod/v3/aigc/text_to_video | Text to video — creates an async task |
| POST | /vod/v3/aigc/image_to_video | Image to video |
| POST | /vod/v3/aigc/text_to_image | Text to image |
| POST | /vod/v3/aigc/image_to_image | Image to image |
| POST | /vod/v3/aigc/video_clone | Video clone |
| POST | /vod/v3/aigc/video_extend | Video extend |
| POST | /vod/v3/aigc/lip_sync | Lip sync |
| POST | /vod/v3/aigc/create_effect_video | Effect video |
| POST | /vod/v3/aigc/recommend/effect | Effect recommendation |
| POST | /vod/v3/aigc/image | Image generation |
| GET | /vod/v3/tasks/{taskId} | Poll task status — read-only, not metered |
| GET | /vod/v3/aigc/effect | List effects — read-only, not metered |
| GET | /vod/v3/aigc/presets-voices | List 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
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
| Field | Meaning |
|---|---|
unit | Always task |
billable_units | 1 for one successfully created task; 0 otherwise |
priced / billing_status | false / no_tariff — no VOD tariff exists yet |
tokens | Always 0 — video is not metered in tokens |
task_id | Upstream task handle, when the response carries one |
cost_drivers | model, duration, resolution, aspectRatio only |
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 port8301, which is not reachable from the public internet (verified: connection timed out), so the default is HTTPS/443. Override withTOKENCOUP_VOD_SCHEME/_HOST/_PORT. - The Bearer scheme is not yet confirmed on this host. Unauthenticated requests, the documented
bce-v3/ALTAK-form andvod-v3/…all returned the sameBceSignatureValidateException, which suggests the gateway on:443expects AK/SK request signing rather than a Bearer key. Do not bill or promise this category until a real key returns200. - The upstream response shape for task creation (the exact
taskIdfield) 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.
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
| Method | Path | Meaning |
|---|---|---|
| POST | /video/generations/qianfan-video | Create 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/list | List 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
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
| Field | Meaning |
|---|---|
unit | Always task |
billable_units | 1 for one successfully created task; 0 otherwise |
priced / billing_status | false / no_tariff — no published tariff yet, no amount produced |
tokens | Always 0 — video is not metered in tokens |
task_id | Upstream task handle |
upstream_usage | Upstream-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.
| Series | Billing mode | Price (RMB) |
|---|---|---|
| VQ4 | per second × resolution | 540p 0.28125/s; 720p 0.59375/s; 1080p 0.75/s; 2K 1.1875/s; 4K 2.4375/s |
| VQ3-Pro | per clip (1–16 s) | 1080p 0.9375; 720p 0.78125; 540p 0.3125 |
| VQ3-Turbo | per clip (1–16 s) | 1080p 0.4375; 720p 0.3750; 540p 0.2500 |
| VQ2 (text/image/first-last-frame) | per duration × resolution | e.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 incremental | 540p 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 output | surcharge | +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.
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.
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.