Cantonese-optimized Speech API — TTS + STT
v1Last updated OpenAPIllms.txtMarkdownAPI Reference
Cantonese speech in and out — one API
Canto-Gen (港嘢) turns Cantonese text into natural, native-sounding speech — nine tones preserved, particles pronounced right. The same key also turns Cantonese audio back into text — file transcription and realtime dictation. OpenAPI 3.1 spec included.
MCP / Agent setup
Canto-Gen provides a Local stdio MCP server (npm package `cantogen-mcp`) that enables zero-hosting-cost local deployment and empowers AI agents with custom voice management and Cantonese TTS generation. After registration, the live tool list is available via `tools/list`. You fill the API key into the config yourself (tick `voices:manage` for voice management); the agent never touches the credentials. Click the button below to copy the setup instructions and hand them to your agent.
Supported AI clients / developer tools
Cloud agents (Manus, Zo Computer, web chat platforms) supported too — the instructions auto-switch to REST mode
Codex
AiderMCP tools
| Tool | Description | Auth Required | Required Scope(s) |
|---|---|---|---|
| get_api_docs | Fetch the live API spec (GET /v1/skill.md, zero auth) | none | |
| list_gallery | List official preset voices (read-only) | sk_ key | tts:generate |
| list_my_voices | List personal voices | sk_ key | voices:manage |
| create_my_voice | Create a personal voice from local audio (plan-gated) | sk_ key | voices:manage |
| delete_my_voice | Delete a personal voice (invalid instantly, can no longer generate; reference audio permanently purged within 30 days; history keeps the name) | sk_ key | voices:manage |
| tts_generate | Generate in preset mode (voice slug) | sk_ key | tts:generate |
| generate_design | Generate in design mode (gender + age) | sk_ key | tts:generatetts:design |
| generate_clone | Generate in clone mode (local reference audio; plan-gated) | sk_ key | tts:generatetts:clone |
| check_job | Poll async job status until done (how to track the async /v1/audio/jobs flow) | sk_ key | tts:generatetts:design |
| cancel_job | Cancel a generation job (not started → full refund; in progress → cancelled after wrap-up, completed portion still billed; settled → the job record is deleted) | sk_ key | tts:generatetts:design |
| asr_transcribe | File transcription (batch, billed by audio duration; long audio auto-converts to async and polls to completion) | sk_ key | tts:generate |
| get_balance | Get the prepaid HKD balance + ASR rates + auto top-up settings (zero cost) | sk_ key | tts:generate |
| get_usage | Audit the wallet ledger (cursor pagination; zero cost) | sk_ key | tts:generate |
| get_asr_vocabulary | Read the account's stored ASR keyword vocabulary (terms + updated_at; needs the asr_vocabulary entitlement) | sk_ key | |
| set_asr_vocabulary | Replace the account's stored ASR keyword vocabulary (whole list; an empty array clears it; needs the asr_vocabulary entitlement) | sk_ key | |
| delete_transcription | Delete one ASR transcription record (and the uploaded audio; immediate effect, no restore) | sk_ key | |
| list_generation_jobs | List your own generation records (GET /v1/audio/jobs; id / status / created_at / voice_slug / duration_ms / text_preview; cursor pagination) | sk_ key | tts:generatetts:design |
| set_telemetry_opt_out | Turn anonymous usage stats on or off (PUT /v1/account/telemetry; off stops automatic behavioural telemetry, ratings and reports still arrive) | sk_ key |
MCP for AI agents
Get a key
API requests authenticate with your Bearer key. Keys are shown exactly once at creation — only a SHA-256 hash is stored server-side, so a lost key must be revoked and replaced.
Create a key in the API Keys page
Open the API Keys page and create a key, then save it straight into an environment variable:
export CANTOGEN_API_KEY="sk_live_..."Key prefixes
| sk_live_… | The only key format. Free-plan keys are also subject to a daily generation limit; any key can also carry an optional monthly credit cap (unset = unlimited). |
Scopes
| tts:generate | Default. Unlocks voice & design generation plus all read endpoints (voice catalog, job polling). |
| tts:clone | Required for clone mode (voice cloning from a reference sample). |
| tts:design | Fine-grained scope for design mode (gender + age synthesized voices) — already covered by tts:generate; either one suffices. |
| voices:manage | Required for personal voice management (MCP list / create / delete my voices). |
Limits attached to every key
Authorization: Bearer $CANTOGEN_API_KEY, except GET /v1/voices (the public catalog, anonymous access).Pricing
API access is available on any paid plan (Lite / Starter / Pro / Creator) at full speed with no daily cap. Free users can create an API key too (50 generation requests per day; polling and downloads don't count) — upgrading unlocks full access.
Async: 1 character = 1 credit, no surcharge
POST /v1/audio/speech) is metered at 1.3×. When the pool runs out, buy credit packs. The X-Credits-Charged response header shows the exact credits billed for each request (multiplier included).Commercial licence — which audio can you use commercially?
Glossary
- Daily generation cap — Free-plan keys: 50 generation submissions per day per product line (TTS and ASR counted separately; polling and downloads don't count). Paid plans have no daily cap.
- Per-key monthly credit cap — A key's month-to-date (UTC) billed-credit cap; exceeding it returns 403 monthly_cap_reached. Unset by default.
- Account credit pool — Account-level character balance shared by the web Creator and the API, resetting each billing cycle; requests return 402 character_limit_reached when exhausted.
- Credit pack — One-time top-up for the account credit pool; never expires.
- Pending-job cap — Concurrent pending jobs per account, tiered by plan (3 / 4 / 5 / 10 / 20 / 20); exceeding returns 429 in_flight_limit_reached.
See /pricing for plan details.
Quickstart
Three minutes to your first job: list the voice catalog → submit a speech job → poll for the result.
List the voice catalog (GET /v1/voices)
curl https://api.canto-gen.com/v1/voices \
-H "Authorization: Bearer $CANTOGEN_API_KEY"{
"voices": [
{
"slug": "sum",
"name": "心妍",
"gender": "female",
"age": "adult",
"styles": [],
"preview_url": "https://canto-gen.com/api/voice-clip?slug=sum"
}
]
}The catalog is live — always pick a slug from your own response. "sum" (心妍) here is the documented example, or browse voices by ear in the Creator gallery.
Submit a speech job (POST /v1/audio/jobs)
# Async by design — submit returns 202 with a job_id, then poll.
export CANTOGEN_API_KEY="sk_live_…"
curl -X POST https://api.canto-gen.com/v1/audio/jobs \
-H "Authorization: Bearer $CANTOGEN_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "cantogen-tts",
"voice": "sum",
"text": "你好,歡迎使用港嘢!",
"response_format": "mp3"
}'Response — 202 Accepted:
HTTP/1.1 202 Accepted
Content-Type: application/json
{
"job_id": "b7e6f2a1-4c3d-4e5f-8a9b-0c1d2e3f4a5b",
"status": "queued",
"poll_url": "/v1/audio/jobs/b7e6f2a1-4c3d-4e5f-8a9b-0c1d2e3f4a5b",
"srt_requested": false
}Async by design — with a sync shortcut
job_id / status / poll_url / srt_requested. No long-lived HTTP connections, no timeouts on long text — poll at your own pace. Short text (≤300 chars, voice/design)? POST /v1/audio/speech returns the audio bytes directly (200) — or an honest 503 pool_cold while the sync queue is busy (nothing billed; waits over ~45 s cancel + refund and return 503 sync_timeout).Voice catalog
The voices and style presets below are synced automatically from the database — add a new voice or preset and this page updates itself. Every voice can be previewed in Creator.
| slug | Name | Gender | Age | Scene | Preview |
|---|---|---|---|---|---|
| keung-gor | 強哥 | male | midage | narration | |
| lok-zai | 樂仔 | male | adult | story | |
| sung-pak | 崇伯 | male | elder | narration | |
| fung-yee | 鳳儀 | female | adult | story | |
| sum-yu | 芯瑜 | female | young | ads | |
| wai | 小慧 | female | adult | story | |
| kay | 凱琪 | female | young | sports | |
| lok | 嘉樂 | male | adult | comedy | |
| sum | 心妍 | female | adult | news | |
| wing-lam-2 | 穎琳 | female | adult | business | |
| bon | 阿邦 | male | adult | narration | |
| ah-sum | 阿森 | male | young | narration | |
| sze-kei | 思琪 | female | midage | narration | |
| hoi | 小海 | male | young | ads | |
| wang-tat | 宏達 | male | young | narration | |
| wing-wing | 詠詠 | female | child | story | |
| ga-ga | 嘉嘉 | female | child | ads | |
| siu-laam | 小藍 | female | child | story | |
| siu-mun | 小滿 | female | child | education | |
| ah-syut | 阿雪 | female | child | education | |
| ah-him | 阿謙 | male | child | education | |
| ah-hei | 阿希 | male | child | narration | |
| siu-yu | 小宇 | male | child | education | |
| so-tai | 蘇太 | female | elder | business | |
| ho-je | 好姐 | female | elder | comedy | |
| gan-suk | 根叔 | male | elder | ads | |
| keung-suk | 強叔 | male | elder | sports | |
| biu-suk | 標叔 | male | elder | comedy | |
| jeun-sing | 晉昇 | male | child | education | |
| tin-lok | 天樂 | male | child | narration | |
| jyut-cing | 悅澄 | female | child | story | |
| tong-tong | 糖糖 | female | child | story | |
| king-je | 瓊姐 | female | elder | comedy | |
| mei-jan | 美珍 | female | elder | narration | |
| sau-ying | 秀英 | female | elder | story | |
| hiu-cing | 曉晴 | female | teen | story | |
| cin-cin | 芊芊 | female | teen | sports | |
| wan-ji | 韻怡 | female | teen | education | |
| jeun-jai | 俊仔 | male | teen | ads | |
| ji-long | 子朗 | male | teen | narration | |
| hin-jai | 軒仔 | male | teen | comedy |
Generation presets (tempo · emotion · timbre)
Presets are generation parameters that pair with any slug above — synced from the same database.
Voice modes
Pick a gallery voice, describe one in text, or clone one from a sample. Each request uses exactly one mode.
Mutually exclusive
voicedefaultGallery voice
Pick a ready-made voice from the Cantonese-optimized gallery by slug.
- Browse GET /v1/voices — every preset is Cantonese-native, with preview clips.
- Pass the slug as voice. sum (心妍) is the documented example — always pick a slug from your own response. Slugs are stable ASCII identifiers (industry standard); Chinese names are for display.
# Async by design — submit returns 202 with a job_id, then poll.
export CANTOGEN_API_KEY="sk_live_…"
curl -X POST https://api.canto-gen.com/v1/audio/jobs \
-H "Authorization: Bearer $CANTOGEN_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "cantogen-tts",
"voice": "sum",
"text": "你好,歡迎使用港嘢!",
"response_format": "mp3"
}'designzero audioDesigned voice
Describe a synthetic voice in plain text — gender + age. No audio files, nothing to upload.
- gender: male | female · age: child | teenage | adult | midage | elder — both required.
- Great for product personas; combine freely with emotion and srt.
curl -X POST https://api.canto-gen.com/v1/audio/jobs \
-H "Authorization: Bearer $CANTOGEN_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "cantogen-tts",
"design": { "gender": "female", "age": "adult" },
"text": "今日天氣幾好,一齊去行山啦。",
"style": "brisk",
"emotion": "happy",
"srt": true
}'clonetts:clone scopeCloned voice
Upload a reference sample — the platform transcribes it internally (ASR) and applies the transcript automatically. Zero extra calls on your side.
- reference_audio: data URL or raw base64 — audio/mpeg, wav, webm, mp4/m4a, ogg. One request is capped at 4.4 MB (≈3 MB of audio once base64-encoded).
- Samples must be at least 3 seconds (shorter is rejected); processing auto-trims to ~15–20 s on sentence boundaries (30 s cap) — a clean sample works best.
- Only reference_audio is needed; the legacy prompt_text field is retired (any value is ignored).
- Requires an API key with the tts:clone scope.
B64=$(base64 -w0 sample.wav)
curl -X POST https://api.canto-gen.com/v1/audio/jobs \
-H "Authorization: Bearer $CANTOGEN_API_KEY" \
-H "Content-Type: application/json" \
-d "{
\"model\": \"cantogen-tts\",
\"clone\": {
\"reference_audio\": \"data:audio/wav;base64,$B64\"
},
\"text\": \"用我把聲講呢句嘢。\"
}"Generation parameters (all modes)
| style | Delivery style — English slugs recommended. Rhythm: steady(平穩) / composed(從容) / rapid(急促) / slow(慢板) / drawl(拖長) / brisk(明快) / dynamic(起伏) / staccato(頓挫). Timbre: mellow(圓潤) / cute(奶音) / sharp(尖細) / lazy(懶音) / breathy(氣聲) / hoarse(沙啞) / deep(洪厚) / crisp(清脆) / feeble(無力) / trembling(顫音). Scene and character slugs are accepted too (corporate / promo / … / storytelling / sports — full list in the OpenAPI schema). The original Chinese preset values (明快 / 圓潤 etc.) remain accepted as aliases — both are normalized internally to the same canonical value; any other free text also passes through. |
| emotion | One of the 11 API English emotion values (see chips below). Note: the API emotion enum (happy / angry / sad / …) and the Creator UI's Chinese emotion gallery (雀躍 / 冷靜 etc., 30+ curation labels) are two different systems — Chinese gallery labels are Creator-only and the API emotion parameter rejects Chinese values; the API exposes only the 11 trained/approved values. |
| instruction | Free-text delivery direction, up to 500 characters. Priority: style → emotion → instruction — instruction has the final say. |
| pitch | Deprecated (2026-09-20): no-op under raw audio delivery (accepted but ignored). Historical range −12…+12 semitones, default 0. |
| volume | Deprecated (2026-09-20): no-op under raw audio delivery (accepted but ignored). Historical range 0–10, default 1. |
| response_format | mp3 (default) / wav. |
| srt | true → the completed job carries an srt field (billed at a higher character rate). Available on all plans. |
Parameter limits
text (async)— POST /v1/audio/jobs text cap: 500 characters; over it returns 400 text_too_long (never truncated).text (sync)— POST /v1/audio/speech cap: 300 billable credits (voice/design); use the async endpoint beyond that.instruction— Free-text delivery instruction cap: 500 characters; over it returns 400 invalid_instruction.style— English slugs (rhythm / timbre / scene / character); the original Chinese presets remain accepted as aliases (both normalize to the same canonical value); any other free text passes through.emotion— One of the 11 closed English enum values (see chips); Chinese values are not accepted.synthesis order— style → emotion → instruction; instruction has the final say.clone.reference_audio— base64 data URL or raw, ≤4.4 MB per request (≈3 MB of audio); only reference_audio is needed — the legacy prompt_text is retired (any value ignored).design— gender (male / female) + age (child / teenage / adult / midage / elder; legacy teen / young still accepted).speed— Removed (2026-10-14) — silently ignored if sent; express speed via the clone `control` descriptor (slow / normal / fast).transcription(文件轉寫)— POST /v1/asr/transcribe — effective per-file cap on the synchronous route is 4.5 MB (platform body limit; Opus 16k fits ≈60 minutes of audio per file); the synchronous delivery cap is 8 minutes (480 seconds) — over it returns 400 audio_too_long (nothing billed); use POST /v1/asr/jobs for long audio (up to 4 hours); no daily audio-duration cap (usage is bounded by plan credits plus the prepaid wallet), but free plans get 50 ASR generation submissions per day, counted separately from TTS (over it returns 429 sandbox_daily_limit); response_format json / text (srt / verbose_json not yet supported).usage(用量明細)— GET /v1/usage — prepaid wallet ledger entries (kind / amount / balance / unit / quantity / rate) with cursor pagination, plus a `summary` block (current period start / characters used / quota / remaining / credit pool / prepaid balance) so you can reconcile without summing entries by hand.asr jobs(非同步提交)— POST /v1/asr/jobs — upfront async: 202 queued on submit, poll GET /v1/asr/transcriptions/{id} for the transcript; multipart (≤4.5 MB), audio_url (server-side fetch, bypasses the 4.5 MB cap) or storage_path (browser session only, up to 500 MB / 4 hours).
Polling & SRT
Jobs settle in seconds for short text. Poll with a 2–5 s backoff until the job completes, then download the pre-signed audio.
POST /v1/audio/jobs202 · job_idGET /v1/audio/jobs/{id}poll · 2–5 s backoffstatus: completedaudio_url readyGET audio_urlpre-signed · no authPoll a job
curl https://api.canto-gen.com/v1/audio/jobs/b7e6f2a1-4c3d-4e5f-8a9b-0c1d2e3f4a5b \
-H "Authorization: Bearer $CANTOGEN_API_KEY"Completed response
{
"job_id": "b7e6f2a1-4c3d-4e5f-8a9b-0c1d2e3f4a5b",
"status": "completed",
"poll_url": "/v1/audio/jobs/b7e6f2a1-4c3d-4e5f-8a9b-0c1d2e3f4a5b",
"srt_requested": true,
"srt": "1\n00:00:00,000 --> 00:00:02,400\n你好,歡迎使用港嘢!",
"audio_url": "https://canto-gen.com/storage/v1/object/sign/audio_history/..."
}// Poll until completed — back off 2–5 s between attempts.
async function pollJob(jobId, maxAttempts = 60) {
for (let i = 0; i < maxAttempts; i++) {
const res = await fetch(`https://api.canto-gen.com/v1/audio/jobs/${jobId}`, {
headers: { Authorization: `Bearer ${process.env.CANTOGEN_API_KEY}` },
});
const job = await res.json();
if (job.status === "completed") return job; // job.audio_url is ready
if (job.status === "failed" || job.status === "cancelled") {
throw new Error(`job ${job.status}`);
}
await new Promise((r) => setTimeout(r, Math.min(2000 + i * 500, 5000)));
}
throw new Error("poll timeout");
}audio_url expires — download promptly
Subtitles (SRT)
Send "srt": true on submit and the completed job's poll response carries an srt field with the subtitle content (as in the completed response above). srt_requested is always present; srt only appears when subtitles were requested and are ready. Subtitles are available on all plans.
Billing nuance
Rate limits & caps
| Response header | Description |
|---|---|
| X-RateLimit-Limit | Per-minute request cap for this key (default 60; configurable at key creation). |
| X-RateLimit-Remaining | Requests left in the current 60-second sliding window. |
| X-RateLimit-Reset | Window reset time (Unix epoch seconds). |
| Retry-After | Attached to 429 responses; wait this many seconds before retrying. |
Monthly credit cap — the key's month-to-date (UTC) usage, counted in credits, must stay under its cap (null = unlimited). Exceeding it returns 403 monthly_cap_reached with a used figure until the month resets. X-RateLimit-* headers are attached to the 202 and 429 responses of POST /v1/audio/jobs and the 429 responses of POST /v1/audio/speech (200 responses carry the usage headers — X-Credits-Charged etc.); the read endpoints (GET /v1/audio/jobs/{id}, GET /v1/voices) are not rate-limited. Both meters are designed to fail open — a metering outage never locks you out.
Transcription (ASR)
Upload an audio file and get the transcript back in the same request — sync-first, with automatic async upgrade for long files. Cantonese-optimized.
Synchronous delivery — one curl
Transcription — upload an audio file and receive the transcript synchronously in the same request. Canonical path: POST /v1/asr/transcribe; OpenAI-compatible clients may keep using Sent as multipart/form-data. Fields: file (required), model (required), language (optional, ISO-639-1), response_format (json default / text). srt and verbose_json need segment-level timestamps and are not yet supported (400 unsupported_response_format). Optional vocabulary (up to 50 terms, keyword biasing, gated by the asr_vocabulary entitlement; silently ignored without it) — when the field is omitted (API key requests) your account's stored vocabulary (PUT /v1/asr/vocabulary) is applied automatically; a request that carries one (including an empty array) takes precedence. Transcription is currently Cantonese-optimized.
curl -X POST https://api.canto-gen.com/v1/asr/transcribe \
-H "Authorization: Bearer \$CANTOGEN_API_KEY" \
-F file=@sample.wav \
-F model=cantogen-asr \
-F response_format=json200 response
{
"id": "b7e6f2a1-4c3d-4e5f-8a9b-0c1d2e3f4a5b",
"object": "transcription",
"text": "今日天氣幾好,一齊去行山啦。",
"duration_seconds": 1830,
"charged_hkd": 0.4067
}Over the 480-second sync delivery cap → 400 audio_too_long
400 audio_too_long (with duration_seconds + async_endpoint, rejected before processing — nothing billed). This route has exactly one success shape; behaviour is a function of the file's duration, not of server load. Long-audio path: POST /v1/asr/jobs (async, up to 4 hours / 500 MB) — returns 202 queued immediately; poll GET /v1/asr/transcriptions/{id} for the transcript. Same wallet billing semantics.Webhook signature verification (callback_url)
Once your account has a webhook signing secret (issued and rotated by support), every callback POST carries two headers: x-canto-signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>." + raw body)> and x-timestamp: <ISO 8601, same second>. Accounts without a secret keep receiving unsigned callbacks (backwards compatible) with an unchanged payload. Three verification rules: (1) verify against the raw body you received — not a re-serialized parsed object; (2) compare in constant time; (3) reject requests whose |now - t| > 300 seconds (replay protection). Rotation: ask support / an admin for a new secret — the old one stops signing immediately; during cutover accept both secrets.
import { createHmac, timingSafeEqual } from "node:crypto";
const SECRET = process.env.CANTOGEN_WEBHOOK_SECRET; // support 俾你嘅 signing secret
const MAX_SKEW_SECONDS = 300;
export function verifyCantoSignature(rawBody, header, now = Math.floor(Date.now() / 1000)) {
const parts = Object.fromEntries(
String(header ?? "").split(",").map((kv) => kv.trim().split("=", 2)),
);
const t = Number(parts.t);
if (!Number.isFinite(t) || Math.abs(now - t) > MAX_SKEW_SECONDS) return false;
const expected = createHmac("sha256", SECRET).update(`${t}.${rawBody}`).digest("hex");
const got = parts.v1 ?? "";
return got.length === expected.length
&& timingSafeEqual(Buffer.from(got), Buffer.from(expected));
}
// Express / Next route handler:一定用 raw body(唔好用 req.body 再 stringify)
// const ok = verifyCantoSignature(rawBody, req.headers["x-canto-signature"]);import hashlib
import hmac
import os
import time
SECRET = os.environ["CANTOGEN_WEBHOOK_SECRET"].encode() # support 俾你嘅 signing secret
MAX_SKEW_SECONDS = 300
def verify_canto_signature(raw_body: bytes, header: str, now: int | None = None) -> bool:
parts = dict(
piece.strip().split("=", 1)
for piece in str(header or "").split(",")
if "=" in piece
)
try:
t = int(parts["t"])
except (KeyError, ValueError):
return False
if abs((now or int(time.time())) - t) > MAX_SKEW_SECONDS:
return False
expected = hmac.new(
SECRET, f"{t}.".encode() + raw_body, hashlib.sha256
).hexdigest()
return hmac.compare_digest(expected, parts.get("v1", ""))
# Flask:用 request.get_data(),唔好用 request.get_json() 再 dump
# ok = verify_canto_signature(request.get_data(), request.headers.get("x-canto-signature"))Billing
Billed by audio duration in credits (1 credit = HK$0.001) — 800 credits/hour (HK$0.80/hour) for file transcription, 1,400 credits/hour (HK$1.40/hour, 1.75×) for realtime dictation, charged per second with no rounding up. Billing order: ① plan monthly credits (resets each billing period; 5,000 on Free) → ② prepaid wallet credits (may overdraw to −HK$5) → ③ with auto top-up enabled, one automatic top-up and retry when short; otherwise 402 insufficient_balance (nothing processed, nothing billed). The estimated amount is held before processing and settled on the actual duration when done; failures, timeouts and outages are refunded in full (success-only billing). File transcription treats audio with no recognizable speech (silence, pure music) as a valid result: it returns 200 with an empty text and is billed on the actual audio duration (mainstream industry convention). GET /v1/balance returns your balance and the current rates (credits and HKD).
Limits
file size— Effective per-file cap on the synchronous route is 4.5 MB (platform request-body limit; exceeding it returns a platform-level 413 — compress first:ffmpeg -i in.* -vn -ac 1 -ar 16000 -c:a libopus -b:a 16k out.ogg; 16 kHz mono Opus 16k fits ≈60 minutes per file).audio duration— The synchronous delivery cap is 8 minutes (480 seconds): probed duration over it returns400 audio_too_long(withduration_seconds+async_endpoint, rejected before processing — nothing billed). UsePOST /v1/asr/jobsfor long audio (async, up to 4 hours / 500 MB). Per-request audio policy cap: 4 hours (over it returns 413).daily cap— No daily audio-duration cap (every plan alike since 2026-10-30) — usage is bounded by the prepaid balance (credits + wallet holds). Free plans also have a 50-submissions-per-day cap per product line (TTS and ASR counted separately).
Balance & rates
Get the prepaid balance (HKD; 1 HK$ = 1,000 credits — the response also carries balance_credits), the file-transcription / realtime-dictation rates in credits and HKD (800 / 1,400 credits per audio hour) and the auto top-up settings. Test keys report the test-environment balance (isolated from production). Top up at /account/billing when the balance runs low (auto top-up can charge a set amount whenever the balance falls below a threshold).
curl https://api.canto-gen.com/v1/balance \
-H "Authorization: Bearer \$CANTOGEN_API_KEY"ASR keyword vocabulary
One list per account — teaches the ASR engine your proper nouns, organisation names and English abbreviations.
Keyword vocabulary (keyword biasing) — one list per account that teaches the ASR engine your proper nouns, organisation names and English abbreviations. Three methods: GET reads it, PUT replaces the whole list, DELETE clears it (same as PUT {"terms": []}). Every key on the account shares one list (per-account, not per-key). The list is cleaned server-side (trimmed, de-duplicated, terms over 30 characters dropped, at most 50 kept) before it is stored, and the response echoes what was actually stored.
Cleanup rules
terms— at most 50 terms (extras are dropped from the front)term length— each term at most 30 characters (longer terms are not stored)cleanup— trims whitespace, normalizes to Unicode NFC, drops duplicates (first occurrence wins)
Read — GET /v1/asr/vocabulary
curl https://api.canto-gen.com/v1/asr/vocabulary \
-H "Authorization: Bearer \$CANTOGEN_API_KEY"{
"scope": "api",
"terms": ["證監會", "庫務局", "Canto-Gen"],
"updated_at": "2026-10-28T09:12:33.000Z"
}Replace — PUT /v1/asr/vocabulary
curl -X PUT https://api.canto-gen.com/v1/asr/vocabulary \
-H "Authorization: Bearer \$CANTOGEN_API_KEY" \
-H "Content-Type: application/json" \
-d '{"terms": ["證監會", "庫務局", "Canto-Gen"]}'Clear — DELETE /v1/asr/vocabulary
curl -X DELETE https://api.canto-gen.com/v1/asr/vocabulary \
-H "Authorization: Bearer \$CANTOGEN_API_KEY"Per-request `vocabulary`
Every request may carry vocabulary (an array of strings) for one-off biasing — POST /v1/asr/transcribe, POST /v1/asr/jobs and POST /v1/asr/realtime/token (realtime dictation) all accept it. API key and browser-session callers may pass it alike (sk_ key or a browser session). An empty array is an explicit override (no biasing for that request); omitting the field means "use the default" (next paragraph).
When the stored list is applied
The stored list is only the default for API key requests: an sk_ transcription request that omits the vocabulary field automatically applies your account's stored list; a request that carries one (including an empty array) takes precedence and never falls back to the stored list. Browser-session (Creator) callers are not affected by that default — a session request without the parameter simply gets no biasing.
Entitlement
asr_vocabulary entitlement). Until it is, all three methods return 403 {"error":"asr_vocabulary_not_granted"} with an actionable message (ask support to enable the feature, then retry). Once it is enabled, a transcription request that carries vocabulary without the entitlement simply has the vocabulary ignored — the transcription itself is unaffected.Realtime WebSocket
Built for interactive, low-latency voice experiences.
Alongside REST, Canto-Gen exposes a WebSocket realtime endpoint for text-in → streamed PCM audio-out: keep one long-lived connection and stream tokens in while audio comes out — built for bring-your-own-LLM voice apps. The protocol is based on OpenAI Realtime; every Canto-Gen extension event and field is marked as such.
wss://api.canto-gen.com/v1/audio/realtime
Auth
Authenticate with the same sk_ API key as REST; the required scope is tts:generate. Prefer the Authorization: Bearer sk_… header. The browser WebSocket API cannot set custom headers, so browsers may fall back to the query parameter ?api_key=sk_… (alias ?token=). Query parameters are written to URLs, server logs and browser history, so keep them browser-only — code running on a server must always use the header.
Events — client → server
| session.update | OpenAI-native | Open/update the session: voice, language, output_audio_format, max_session_chars, tts.segmentation (`max_session_chars` may also be supplied at connect time via the `?max_session_chars=` query parameter; it is always clamped to the plan cap). |
| conversation.item.create | OpenAI-native | Send one explicit utterance (input_text); triggers synthesis. |
| input_text.append | Canto-Gen extension | Send raw token deltas — stream as you generate. |
| input_text.commit | Canto-Gen extension | Force a segment boundary (flush now). |
| response.create | OpenAI-native | Trigger synthesis. |
| response.cancel | OpenAI-native | Barge-in: stop the current utterance and refund it. |
| session.close | Canto-Gen extension | Close the session and settle. |
Events — server → client
| session.created | OpenAI-native | Session opened; carries the server-minted session id and the **effective** `max_session_chars` (already clamped to the plan cap). |
| session.updated | OpenAI-native | Config ack. |
| response.created | OpenAI-native | An utterance begins. |
| response.output_audio.delta | OpenAI-native | A base64 PCM16 @ 48 kHz audio chunk. |
| response.output_audio.done | OpenAI-native | Utterance audio complete. |
| response.done | OpenAI-native | Utterance done; usage carries input_chars / billed_chars / remaining (extension fields). |
| error | OpenAI-native | {type, code, message, http_status}. |
Segmentation (tts.segmentation)
tts.segmentation (extension) controls utterance segmentation: {"mode":"server"} (default) lets the server split on punctuation and synthesize utterance by utterance — the client just keeps appending tokens; {"mode":"client"} lets the client mark boundaries itself via conversation.item.create / input_text.commit. Optional min_chars / max_chars / punctuation.
Limits & timeouts
billing— Per utterance (reserve → complete/refund); actually billed = ceil(input characters × 1.5) (WS realtime multiplier as of 2026-11-08; SSOT = constants.ts WS_REALTIME_CHARACTER_MULTIPLIER). Failures and barge-ins are refunded automatically. `response.done` usage: `input_chars` = raw input, `billed_chars` = actually billed (multiplier included), `remaining` = balance.idle_timeout— Idle 120 s (no app-level activity) → the server closes the connection and settles.max_session_duration— Free plan: a single session lasts at most 5 minutes; paid plans have no duration cap. It is closed at the cap.max_sessions_per_user— Concurrent sessions per user are plan-tiered: free 1 / lite 2 / starter 3 / pro 4 / studio 5 / enterprise 5; unknown plans are treated as free.max_sessions_global— At most 8 concurrent sessions platform-wide.max_session_chars— Input-character cap per session (**2,000 free / 20,000 paid**; measured on input characters — actual billing multiplies by the WS ×1.5 rate, see billing); server-side clamp — a client may request a lower value via `session.update` (or the `?max_session_chars=` connect-time query parameter) but never more than the plan cap; exceeding it returns session_char_limit_exceeded. The effective value is echoed in `session.created` (no need to send `session.update` first to learn it).max_in_flight— At most 3 un-settled utterances per session.raw_ingress— Raw input cap of 20,000 characters per session and 5,000 per minute (punctuation and whitespace included); exceeding it returns raw_limit_exceeded, fail-closed.lease— Each utterance carries a 60-second settlement lease; if it is not settled in time it is refunded automatically.rate_limit / monthly_cap— Per-user per-minute rate limit (all keys on the account count together — extra keys never raise the total; each key also has its own tighter cap); the monthly credit cap is per key. Usage is recorded one row per utterance.daily_generation_limit— Free plan: 50 generation submissions per day per product line (TTS and ASR counted separately; polling and downloads don't count); exceeding it returns sandbox_daily_limit (429). Paid plans have no daily cap.frame_size— Single WS message cap: 64 KiB.heartbeat— The server pings periodically; pings do not count as app activity.
// npm i ws — one long-lived connection: stream tokens in, stream PCM out.
import WebSocket from "ws";
const ws = new WebSocket("wss://api.canto-gen.com/v1/audio/realtime", {
headers: { Authorization: `Bearer ${process.env.CANTOGEN_API_KEY}` },
});
ws.on("open", () => {
ws.send(JSON.stringify({
type: "session.update",
session: { voice: "sum", language: "yue", output_audio_format: "pcm16", max_session_chars: 500 },
}));
// One explicit utterance — or keep sending input_text.append deltas.
ws.send(JSON.stringify({
type: "conversation.item.create",
item: { type: "message", content: [{ type: "input_text", text: "你好,歡迎使用港嘢!" }] },
}));
});
const chunks = [];
ws.on("message", (raw) => {
const ev = JSON.parse(raw.toString());
if (ev.type === "session.created") console.log("session", ev.session.id);
if (ev.type === "response.output_audio.delta") chunks.push(Buffer.from(ev.delta, "base64"));
if (ev.type === "response.done") {
// PCM16 @ 48 kHz — feed an AudioWorklet or write the chunks to disk.
console.log("billed", ev.response.usage.billed_chars, "remaining", ev.response.usage.remaining);
ws.close();
}
if (ev.type === "error") console.error(ev.error.code, ev.error.message);
});Error codes
| invalid_api_key | 401 | Key missing, invalid, expired, or wrong scope. |
| rate_limit_exceeded | 429 | Per-user per-minute limit hit (all keys on the account count together); carries retry_after. |
| sandbox_daily_limit | 429 | Free plan's 50 generation submissions per day are used up for this product line (TTS and ASR counted separately); try again tomorrow or upgrade. |
| monthly_cap_reached | 429 | The key's monthly credit cap is reached. |
| character_limit_reached | 402 | Account credit pool exhausted — the utterance is not synthesized. |
| concurrency_limit_reached | 429 | Concurrent session or un-settled utterance cap reached. |
| session_char_limit_exceeded | 403 | This session's character cap is reached. |
| raw_limit_exceeded | 413 | Raw input volume (including punctuation/whitespace) exceeds the cap. |
| text_too_long | 400 | A single utterance exceeds the length limit. |
| invalid_session | 400 | The session is closed or otherwise invalid. |
| engine_unavailable | 503 | The realtime engine is temporarily unavailable; retry. |
Realtime Transcription WebSocket
Realtime dictation — live captions, voice-agent transcription and other low-latency scenarios.
Realtime dictation — one long-lived connection streams PCM audio in and transcription out: transcription.delta is an incremental, append-only chunk (monotonic — published text is never revised; roughly every 2s) and transcription.done is the final full text. Ideal for live captions and voice-agent transcription. 1,400 credits/audio-hour (HK$1.40/audio-hour; 1 HK$ = 1,000 credits) (1.75× batch), per second, success-only. After the final commit the gateway closes on done (≤6s fallback). Language: optional ?profile=<id> query (auto-v1 / yue-zh-en-mixed-v1 / yue-trad-v1 / zh-cmn-v1 / en-v1; unknown → 1008 invalid_profile).
wss://api.canto-gen.com/v1/asr/realtime
Auth
Server-side: Authorization: Bearer sk_…. Browsers: never put the permanent API key in a URL — mint a short-lived ephemeral token (cst_…, 60–600s, default 300) server-side via POST /v1/asr/realtime/token and open the WS with ?token=<cst_…> (canonical; ?api_key= is still accepted as a transitional alias — renamed on the gateway 2026-10-21, both verified end-to-end). Optional vocabulary (keyword biasing, up to 50 terms, gated by the asr_vocabulary entitlement; silently ignored without it) — both sk_ and session callers may pass it.
curl -X POST https://api.canto-gen.com/v1/asr/realtime/token \
-H "Authorization: Bearer \$CANTOGEN_API_KEY" -H "Content-Type: application/json" \
-d '{"expires_in_seconds":300}'Protocol sequence
| server ▶ you | {"type":"gateway.welcome","rate_hkd_per_hour":1.4,…} |
| server ▶ you | {"type":"session.created",…} |
| you ▶ server | {"type":"session.update","model":"asr"} |
| you ▶ server | {"type":"input_audio_buffer.commit","final":false} |
| you ▶ server | {"type":"input_audio_buffer.append","audio":"<b64>"} × N |
| server ▶ you | {"type":"transcription.delta","delta":"…"} |
| you ▶ server | {"type":"input_audio_buffer.commit","final":true} |
| server ▶ you | {"type":"transcription.done","text":"…"} |
Audio format & resampling
Audio = PCM16LE mono 16 kHz base64 (32,000 bytes = 1 second); ≤640KB per frame and ≤640KB/s average. Wrong sample rate yields garbage transcription billed by received bytes — resampling is the client's responsibility (industry standard): browsers use new AudioContext({ sampleRate: 16000 }) for mic capture; Node/files use ffmpeg -i in.any -f s16le -ar 16000 -ac 1 out.pcm. gateway.close (code + reason) arrives right before the socket closes. Declare the format via connect query: ?sample_rate=8000–48000&channels=1|2. Container files (WAV/MP3/Ogg/FLAC) are rejected with 4010 invalid_audio_format (zero charge) — send raw PCM16LE.
Billing & limits
billing— 1,400 credits/audio-hour (HK$1.40/audio-hour; 1 HK$ = 1,000 credits; 1.75× batch), per second, no rounding up; balance checked before connect (below one tick → 4002); in-arrears hold every 60 seconds mid-session (insufficient → 4009); settled on actual audio seconds at disconnect (billed == audio). Realtime usage is accounted separately from batch transcription usage.max_sessions_global— 10 concurrent sessions platform-wide; 2 per key on free, 4 per key on paid.session duration / idle— No session-duration cap (removed for every plan on 2026-10-30); idle (no client frame) closes after 120s; a billing tick every 60s holds the next chunk and closes the session when the balance runs out (4009).format declaration— Connect query?sample_rate=8000–48000&channels=1|2— billable seconds are computed at the declared byte rate; omitting = the 16 kHz mono contract.
WS close codes
| 1000 | completed | Normal completion (done received). |
| 1001 | idle_timeout | No client frame within 120s. |
| 1008 | protocol_violation | Bad protocol / binary frames / invalid base64 / rate exceeded. |
| 1009 | message_too_big | Single frame above 640KB. |
| 1011 | engine_lost | Engine disconnected mid-session. |
| 1013 | engine_unavailable | Engine unreachable. |
| 4001 | invalid_or_expired_token | Key invalid / expired / revoked. |
| 4002 | insufficient_balance | Balance below one tick before connect. |
| 4008 | capacity_exceeded | Concurrent session cap hit (global 10 / per-key free 2 / paid 4). |
| 4009 | insufficient_balance | Balance insufficient for the next hold mid-session. |
| 4010 | invalid_audio_format | Container file detected (WAV/Ogg/FLAC/MP3) — send raw PCM16LE mono 16 kHz instead. |
// npm i ws — one long-lived connection: stream PCM in, transcript out.
import WebSocket from "ws";
const ws = new WebSocket("wss://api.canto-gen.com/v1/asr/realtime", {
headers: { Authorization: `Bearer ${process.env.CANTOGEN_API_KEY}` },
});
ws.on("open", () => {
ws.send(JSON.stringify({ type: "session.update", model: "asr" }));
ws.send(JSON.stringify({ type: "input_audio_buffer.commit", final: false }));
// feed 16 kHz mono s16LE chunks as they come off the mic / file
ws.send(JSON.stringify({ type: "input_audio_buffer.append", audio: pcmChunk.toString("base64") }));
});
ws.on("message", (raw) => {
const ev = JSON.parse(raw.toString());
if (ev.type === "transcription.delta") process.stdout.write(ev.delta);
if (ev.type === "transcription.done") { console.log(ev.text); ws.close(); }
});Errors
Errors use a stable machine-readable error code plus an optional human-readable message.
{
"error": "text_too_long",
"message": "text exceeds 500 characters."
}| HTTP | error code | Cause | Fix |
|---|---|---|---|
| 400 | invalid_model | model must be "cantogen-tts" (or omitted). | Omit model or set "cantogen-tts". |
| 400 | voice_mode_conflict | More than one of voice / design / clone was sent — the three modes are mutually exclusive. | Send exactly one voice mode per request. |
| 400 | text_required | text is missing or empty. | Include a non-empty text (1–500 characters). |
| 400 | text_too_long | text exceeds 500 characters. | Split the text — over-limit requests are rejected, not truncated. |
| 400 | unsupported_format | response_format must be mp3 or wav. | Use mp3 or wav. |
| 400 | invalid_pitch | pitch must be between −12 and +12 semitones. | Adjust pitch to the valid range. |
| 400 | invalid_volume | volume must be between 0 and 10. | Adjust volume to the valid range. |
| 400 | invalid_emotion | emotion is not one of the 11 supported API values. | Use one of the supported English API emotion values (Creator Chinese labels such as 雀躍 / 冷靜 are not API enum values). |
| 400 | invalid_srt | srt must be a boolean. | Use true / false. |
| 400 | reference_audio_required | clone.reference_audio is missing. | Attach a base64 reference sample. |
| 400 | invalid_reference_audio | clone.reference_audio is not valid base64 audio. | Send a data URL (data:audio/…;base64,…) or raw base64. |
| 400 | invalid_reference_audio_size | clone.reference_audio exceeds ~3 MB of audio (the JSON API's per-request cap). | Trim the sample (3 s or more is enough) and retry. |
| 400 | spoken_text_required | text has no speakable content — zero billable credits (only punctuation / whitespace / emoji / tone tags). | Include text with readable words. |
| 400 | design_gender_and_age_required | Both design.gender and design.age are required. | Provide both fields. |
| 400 | invalid_job_id | The poll or cancel id is not a UUID. | Check the job_id. |
| 400 | invalid_request | The body is not valid JSON, or a non-JSON Content-Type was sent (/v1 accepts application/json only); for transcription, multipart is missing `file`/`model`, the file is empty, or the audio type is unsupported. | Send Content-Type: application/json with a valid JSON body. |
| 413 | payload_too_large | The request exceeds its size cap — 4.4 MB for the JSON API (clone reference samples); 4.5 MB for synchronous transcription (platform request-body cap); up to 500 MB via async jobs (audio_url / storage_path). | Sync: compress to 16 kHz mono Opus 16k (≈33–40 min per 4.5 MB) or switch to POST /v1/asr/jobs (audio_url / storage_path up to 500 MB). |
| 401 | invalid_or_expired_token | API key missing, invalid, expired, or revoked. | Create a new key and check the Bearer header. |
| 402 | character_limit_reached | The account credit pool cannot cover this generation (the body includes remaining). | Buy a credit pack or wait for the monthly reset. |
| 403 | insufficient_scope | The key lacks the required scope (cloning needs tts:clone); the body includes "scope". | Create a key with the required scope. |
| 403 | monthly_cap_reached | The key's monthly credit cap is reached; the body includes "used". | Wait for the UTC month to reset or raise the cap. |
| 404 | job_not_found | No job with this id (or it belongs to another key). | Check the job_id and the key used to submit. |
| 409 | already_settled | The job already settled (completed/failed/cancelled) and can no longer be cancelled; no refund applies. | Poll GET /v1/audio/jobs/{id} for the final state instead. |
| 409 | duplicate_request | The same Idempotency-Key (alias x-idempotency-key) was already submitted (retry safety: nothing was re-billed). | Poll the original job_id, or submit with a new key. |
| 404 | not_found | No such endpoint (typo in the path). | Check the paths in /v1/openapi.json. |
| 403 | batch_requires_pro | Bulk generation (items) requires the Starter/Pro/Creator plan. Concurrent pending jobs are tiered by plan (3 / 4 / 5 / 10 / 20 / 20 pending on free/lite/starter/pro/studio/enterprise); exceeding the cap returns 429 in_flight_limit_reached. | Wait for current jobs to finish, or upgrade to Starter/Pro/Creator for bulk generation and a higher concurrency cap. |
| 429 | capacity_exceeded | The public API generation pool is at its global concurrency cap. | Wait Retry-After seconds, or use the async `POST /v1/audio/jobs` path. |
| 429 | rate_limit_exceeded | Per-user per-minute limit hit (all keys on the account count together). | Wait Retry-After seconds (also mirrored in the body as retry_after), then retry. |
| 503 | service_unavailable | The voice engine is temporarily offline (maintenance or backend not ready) — the request was rejected before acceptance and nothing was billed. The response carries Retry-After. | Wait Retry-After seconds (default 60) and retry; failures are never billed. |
| 503 | rate_limit_unavailable | The rate-limit service is temporarily unavailable — the request was rejected before acceptance (nothing billed) rather than letting ungoverned traffic through. The response carries Retry-After. | Wait Retry-After seconds (default 5) and retry. |
| 429 | sandbox_daily_limit | Free plan: the daily limit of 50 generation submissions has been reached for this product line (TTS and ASR are counted separately); polling and downloads are unaffected. | Try again tomorrow, or upgrade to the Lite plan for full API access. |
| 429 | api_busy | The API generation queue is at its global capacity cap (rejected before reserve — nothing billed). | Wait a few seconds and retry. |
| 502 | audio_delivery_failed | Generation completed but the audio could not be fetched. | Poll GET /v1/audio/jobs/{id} and download the audio_url instead. |
| 503 | sync_generation_failed | The job failed or was cancelled during the sync wait (already refunded automatically). | Retry via POST /v1/audio/jobs (async). |
| 503 | reference_upload_failed | The clone reference audio could not be stored temporarily. | Simply retry. |
| 503 | voice_gallery_unavailable / jobs_unavailable | Transient backend issue. | Retry with backoff. |
| 400 | unsupported_response_format | Transcription response_format currently supports json / text only — srt / verbose_json need segment-level timestamps and are not yet available. | Use json or text. |
| 402 | insufficient_balance | The plan credits quota and prepaid wallet together cannot cover the hold for this transcription (nothing processed, nothing billed). | Top up at /account/billing or buy a credit pack, then retry (failed requests are never billed). |
| 503 | engine_unavailable | The transcription service is temporarily unavailable (duration-probe, billing or pipeline failure; engine queueing/degradation within the sync window — transient). Any hold is refunded in full. | Retry after Retry-After seconds; nothing is billed. |
| 400 | audio_too_long | Audio exceeds the 8-minute (480-second) synchronous delivery cap — rejected before processing, nothing billed (response carries duration_seconds + async_endpoint). | Use POST /v1/asr/jobs (async, up to 4 hours / 500 MB). |
| 400 | storage_path_session_only | An API-key caller sent `storage_path` — that entry mode is browser-session only (the Creator large-file lane). | Use the audio_url or multipart file entry instead. |
| 403 | storage_path_forbidden | `storage_path` does not belong to the authenticated user (cross-account guard). | Only use a path returned by /api/asr/upload-url for your own session. |
| 404 | storage_path_not_found | The object referenced by `storage_path` does not exist (upload incomplete or past its TTL — 24 hours on free / 7 days on paid). | Re-upload via /api/asr/upload-url and submit again. |
| 503 | sync_timeout | The speech sync fast lane exceeded its ~45 s wait — the job was cancelled and will be refunded within seconds (response carries Retry-After; X-Request-Id kept for reconciliation). | Retry shortly, or use POST /v1/audio/jobs (async). |
Infrastructure
Built to stay fast when it matters.
API speech workloads run on a dedicated GPU pool — fully isolated from the interactive Creator, so your production traffic and someone's browser session never compete for the same capacity.
Account & usage
Three surfaces an API-only customer can use without the web console — generation records, the anonymous-usage-stats switch, and self-service account deletion.
Three account surfaces that an API-only customer can use without logging into the web console — review your own generation records, turn anonymous usage stats on or off, and (irreversibly) delete your own account. All three are owner-scoped: they only ever show or touch your own account.
Generation records — GET /v1/audio/jobs
List your own generation records (newest first) — an API-only customer can review what they submitted and how long it took without logging into the web console. Every record carries a bounded text preview (max 120 characters); read the full text with GET /v1/audio/jobs/{id} or keep your own copy. The key needs the tts:generate or tts:design scope (otherwise 403 insufficient_scope).
curl "https://api.canto-gen.com/v1/audio/jobs?limit=20" \
-H "Authorization: Bearer \$CANTOGEN_API_KEY"{
"jobs": [
{
"id": "b7e6f2a1-4c3d-4e5f-8a9b-0c1d2e3f4a5b",
"status": "done",
"created_at": "2026-10-29T09:12:00.000Z",
"voice_slug": "sum",
"duration_ms": 4200,
"text_preview": "你好,歡迎使用港嘢!"
}
],
"next_before": null
}limit— rows per page (1–100, default 20)before— cursor — theidof the last record on the previous page (a uuid)status— optional filter: queued / processing / cancelling / done / error / cancellednext_before— cursor for the next page;null= no further pagetext_preview— bounded preview of the generated text (max 120 characters)duration_ms— audio duration in milliseconds (nulluntil the audio exists)
⚠️ status uses the raw job status values (done / error / …), while the polling surface GET /v1/audio/jobs/{id} uses the public names (completed / failed / …) — check which endpoint you are reading.
Anonymous usage stats — GET / PUT /v1/account/telemetry
Read or update this account's anonymous usage stats (quality signal) setting. telemetry_opt_out: true turns off automatic behavioural telemetry (for example how you use the service); feedback you submit on purpose (ratings, reports) is not affected — that is an explicit request, not telemetry. One setting per account (every key on the account shares the same user_profiles.telemetry_opt_out).
curl https://api.canto-gen.com/v1/account/telemetry \
-H "Authorization: Bearer \$CANTOGEN_API_KEY"{
"telemetry_opt_out": false
}curl -X PUT https://api.canto-gen.com/v1/account/telemetry \
-H "Authorization: Bearer \$CANTOGEN_API_KEY" \
-H "Content-Type: application/json" \
-d '{"telemetry_opt_out": true}'{
"ok": true,
"telemetry_opt_out": true
}Delete your account — POST /v1/account/deletion
Delete your own account (self-service deletion — available to API-only customers without the web console). Two-step confirmation: body { confirmEmail, confirmWord } — confirmEmail must equal your account email (case-insensitive) and confirmWord must equal DELETE (case-sensitive). On success the account is deactivated immediately (login banned, every existing session invalidated) and personal data is removed by the daily cleanup job — permanently purged within 30 days (purge_by is the deadline by which the purge completes).
curl -X POST https://api.canto-gen.com/v1/account/deletion \
-H "Authorization: Bearer \$CANTOGEN_API_KEY" \
-H "Content-Type: application/json" \
-d '{"confirmEmail": "you@example.com", "confirmWord": "DELETE"}'{
"ok": true,
"purge_by": "2026-11-02T03:00:00.000Z"
}What gets purged: generation records, voices, reference audio and other personal data are removed; encrypted backups rotate out on the provider's cycle (they are not cleared immediately); billing and usage records are retained by law (they are not removed when the account is deleted). Team accounts have to be dissolved first — owning a workspace that still has other members returns 409 team_owner (dissolve or hand it over first); unfinished generation jobs return 409 active_jobs. Repeat requests are idempotent (one deletion request per account).
Error codes
| HTTP | error | Cause |
|---|---|---|
| 400 | invalid_limit | `limit` is not an integer between 1 and 100. |
| 400 | invalid_cursor | `before` is not a uuid, or it does not match any of your records. |
| 400 | invalid_status | `status` is outside the allowed set (queued / processing / cancelling / done / error / cancelled). |
| 400 | invalid_telemetry_opt_out | `telemetry_opt_out` is not a boolean. |
| 400 | confirm_missing | The deletion body is missing `confirmEmail` or `confirmWord`. |
| 400 | confirm_email_mismatch | `confirmEmail` does not match your account email (compared case-insensitively). |
| 400 | confirm_word_mismatch | `confirmWord` is not `DELETE` (case-sensitive). |
| 401 | invalid_or_expired_token | API key missing, invalid, expired, or revoked. |
| 403 | insufficient_scope | The key lacks the `tts:generate` or `tts:design` scope (the generation-record list). |
| 409 | active_jobs | You still have unfinished generation jobs (queued / processing / cancelling) — wait for them to finish. |
| 409 | team_owner | You own a workspace that still has other members — dissolve or hand it over first. |
| 503 | jobs_unavailable | The generation-record list is temporarily unavailable (`GET /v1/audio/jobs`). |
| 503 | telemetry_read_failed | The anonymous-usage-stats setting is temporarily unreadable. |
| 503 | telemetry_update_failed | The anonymous-usage-stats setting could not be saved temporarily. |
| 503 | deletion_request_failed | The deletion request could not be recorded temporarily — retry later (retries are idempotent). |
Data retention & deletion
Exactly how your text, audio and outputs are kept and when they are removed — one page, and the numbers match our retention framework.
Retention & deletion rules
| Data | Retention / deletion |
|---|---|
| Generated content (job records with text, generated audio, ASR transcripts) | 90 days, then removed by the daily automatic cleanup |
| Data you delete (a voice, an individual record, a transcript or audio file) | Effective immediately, no restore, permanently purged within 30 days |
| Unregistered reference audio (uploaded but not bound to any job) | 24-hour grace window, then removed within 30 days |
| Reference audio of a registered voice | Kept for as long as the voice exists; deleting the voice takes effect immediately and the files are purged within 30 days |
| Meeting records (meeting audio, meeting transcripts) | Exempt from the automatic sweep — they follow the account lifecycle and are removed only when you delete them or your account |
| Account deletion | Disabled immediately (no further login or API calls), fully purged within 30 days |
| Backups | Encrypted backups are removed on the provider's rotation cycle |
Deletion always removes the database record first and the audio object afterwards — the data stops being usable immediately and there is no restore.
Data location & sub-processors
Data is hosted in South Korea (Seoul), with backups managed in the same region. Sub-processors: Supabase (hosted database and storage) and Stripe (payments — they never touch your content). Speech generation runs on our own cloud infrastructure, with no additional third parties.
Never used for training
Delete a transcription
Delete one ASR transcription (including the audio you uploaded): DELETE /v1/asr/transcriptions/{id}. The id is the one returned by POST /v1/asr/transcribe / POST /v1/asr/jobs. You can only delete records owned by your key; an unknown or foreign id returns 404 (which does not reveal whether the id exists).
curl -X DELETE https://api.canto-gen.com/v1/asr/transcriptions/<id> \
-H "Authorization: Bearer \$CANTOGEN_API_KEY"Delete one of your voices
Delete one of your own voices: DELETE /v1/voices/{id} (the {id} is the voice's slug or id). The voice disappears from every listing immediately and can no longer be used for generation; the reference audio and the prepared-reference copies of it are removed right away — there is no restore. Official preset voices cannot be deleted (same 404 — their existence is never revealed); the key needs the voices:manage scope. If a generation job is still running for that voice, the request returns 409 voice_busy and nothing is deleted — delete it again once the job has finished.
curl -X DELETE https://api.canto-gen.com/v1/voices/<voice-slug> \
-H "Authorization: Bearer \$CANTOGEN_API_KEY"Delete a generation record
Delete one generation record: DELETE /v1/audio/jobs/{id} (the {id} is the job_id returned by POST /v1/audio/jobs). If the job has not finished yet (queued / processing), the route still cancels it (the refund semantics are unchanged); if it already completed, failed or was cancelled, the job record (including the text you generated), the audio file and its subtitle sidecars are deleted. Deletion always removes the database record first and the audio object afterwards — the data stops being usable immediately and there is no restore.
curl -X DELETE https://api.canto-gen.com/v1/audio/jobs/<job_id> \
-H "Authorization: Bearer \$CANTOGEN_API_KEY"Reference & downloads
This guide is the step-by-step walkthrough; /v1/docs/reference is the detailed API Reference — full request/response schemas for every endpoint, copy-paste cURL calls and all error codes. Everything on this page also ships in machine-readable form.
/v1/audio/speech200 syncShort-text synchronous generation — 200 audio bytes (voice/design, ≤300 chars).
Full schema → API reference/v1/audio/jobs202 asyncSubmit a speech job (single or bulk ≤25; bulk requires Starter or above). Returns 202 with job_id(s) and poll_url.
Full schema → API reference/v1/audio/jobs/{id}pollPoll a job; when completed the response carries a pre-signed audio_url.
Full schema → API reference/v1/audio/jobslistList your own generation records (newest first). Owner-scoped: `limit` (1–100, default 20) with `before` cursor pagination and an optional `status` filter; returns `id` / `status` / `created_at` / `voice_slug` / `duration_ms` / `text_preview` (≤120 chars).
Full schema → API reference/v1/voicesList the Cantonese-optimized voice catalog, with preview clips. This endpoint allows anonymous access.
Full schema → API reference/v1/voices/{id}deleteDelete one of your own voices (slug or id) — hidden immediately, no longer usable for generation, files purged right away. Official preset voices cannot be deleted.
Full schema → API reference/v1/audio/jobs/{id}cancel / deleteA job that is still running is cancelled (refunded); a settled job has its record deleted (job record + audio + subtitle sidecars).
Full schema → API reference/v1/asr/transcribe200 syncTranscribe audio to text synchronously; billed by audio duration — 800 credits/hour (HK$0.80/hour; 1 HK$ = 1,000 credits), success-only.
Full schema → API reference/v1/asr/jobs202 asyncSubmit a transcription job — 202 queued immediately; multipart upload, audio_url (server-side fetch) or storage_path (browser-session large-file lane, up to 500 MB). Best for long audio.
Full schema → API reference/v1/asr/transcriptions/{id}pollRetrieve a transcription job (queued → processing → completed/failed); completed carries the transcript.
Full schema → API reference/v1/balanceGet the prepaid balance (HKD), transcription/dictation rates and auto top-up settings.
Full schema → API reference/v1/asr/vocabularyreadRead your account's ASR keyword vocabulary (one list, per account). `terms` is the cleaned term list; `updated_at` is when it was last changed (null if never set).
Full schema → API reference/v1/asr/vocabularyreplaceReplace your account's ASR keyword vocabulary (whole-list replacement, not an increment). `terms` is cleaned first (trimmed, de-duplicated, over-long terms dropped, at most 50 kept) and then stored; the response echoes what was actually stored.
Full schema → API reference/v1/asr/vocabularyclearClear your account's ASR keyword vocabulary (same as `PUT {"terms": []}`). API key transcription requests that carry no `vocabulary` parameter will then apply no terms.
Full schema → API reference/v1/account/telemetryreadRead this account's anonymous-usage-statistics (quality signal) setting → `{ telemetry_opt_out }`. One setting per account (`user_profiles.telemetry_opt_out`).
Full schema → API reference/v1/account/telemetryopt-outTurn this account's anonymous usage stats on or off (body `{ telemetry_opt_out: boolean }`). `true` turns off automatic behavioural telemetry; feedback you submit on purpose is not affected.
Full schema → API reference/v1/account/deletionirreversibleDelete your own account (self-service). Two-step confirmation body `{ confirmEmail, confirmWord }`; on success returns `{ ok, purge_by }` — the account is deactivated immediately and personal data is purged within 30 days.
Full schema → API reference# OpenAPI 3.1 spec — generate a typed client in your language
curl https://canto-gen.com/v1/openapi.json
# This page as clean Markdown
curl https://canto-gen.com/v1/docs/en.md
# Agent index (llms.txt)
curl https://canto-gen.com/llms.txtCopy this page as Markdown, or grab the Markdown / llms.txt / OpenAPI machine-readable versions.