Canto-X1 情緒控制升級 — 11 種情緒,更傳神
廣東話出圖、剪輯、Gen片一條龍!1/1 截止

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

Claude CodeClaude CodeOpenCodeOpenCodeCodexCodexGemini CLIGemini CLICursorCursorCopilotCopilotClineClineAiderAider

MCP tools

ToolDescriptionAuth RequiredRequired Scope(s)
get_api_docsFetch the live API spec (GET /v1/skill.md, zero auth)none
list_galleryList official preset voices (read-only)sk_ keytts:generate
list_my_voicesList personal voicessk_ keyvoices:manage
create_my_voiceCreate a personal voice from local audio (plan-gated)sk_ keyvoices:manage
delete_my_voiceDelete a personal voice (invalid instantly, can no longer generate; reference audio permanently purged within 30 days; history keeps the name)sk_ keyvoices:manage
tts_generateGenerate in preset mode (voice slug)sk_ keytts:generate
generate_designGenerate in design mode (gender + age)sk_ keytts:generatetts:design
generate_cloneGenerate in clone mode (local reference audio; plan-gated)sk_ keytts:generatetts:clone
check_jobPoll async job status until done (how to track the async /v1/audio/jobs flow)sk_ keytts:generatetts:design
cancel_jobCancel a generation job (not started → full refund; in progress → cancelled after wrap-up, completed portion still billed; settled → the job record is deleted)sk_ keytts:generatetts:design
asr_transcribeFile transcription (batch, billed by audio duration; long audio auto-converts to async and polls to completion)sk_ keytts:generate
get_balanceGet the prepaid HKD balance + ASR rates + auto top-up settings (zero cost)sk_ keytts:generate
get_usageAudit the wallet ledger (cursor pagination; zero cost)sk_ keytts:generate
get_asr_vocabularyRead the account's stored ASR keyword vocabulary (terms + updated_at; needs the asr_vocabulary entitlement)sk_ key
set_asr_vocabularyReplace the account's stored ASR keyword vocabulary (whole list; an empty array clears it; needs the asr_vocabulary entitlement)sk_ key
delete_transcriptionDelete one ASR transcription record (and the uploaded audio; immediate effect, no restore)sk_ key
list_generation_jobsList your own generation records (GET /v1/audio/jobs; id / status / created_at / voice_slug / duration_ms / text_preview; cursor pagination)sk_ keytts:generatetts:design
set_telemetry_opt_outTurn 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

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.

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.

1

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:

environmentbash
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:generateDefault. Unlocks voice & design generation plus all read endpoints (voice catalog, job polling).
tts:cloneRequired for clone mode (voice cloning from a reference sample).
tts:designFine-grained scope for design mode (gender + age synthesized voices) — already covered by tts:generate; either one suffices.
voices:manageRequired for personal voice management (MCP list / create / delete my voices).

Limits attached to every key

TTS generation requests carry a per-minute rate limit (default 60 requests) and an optional monthly credit cap (per key). ASR (transcription / realtime dictation) has no daily or per-key cap and draws from the same credits pool as TTS (plan monthly credits first, then the prepaid wallet, then an automatic top-up if enabled). All REST endpoints authenticate with 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

API usage draws from the same account credit pool as the web Creator, resetting on your billing cycle — the async API bills 1 character = 1 credit, no multiplier, no surcharge; realtime (sync 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?

Audio generated during a paid period (subscription, credit pack, or API usage) is free for personal and commercial use, perpetually (survives cancellation). Free-plan audio is personal, non-commercial use only — upgrading never licenses it retroactively. Preset voices and voice models remain Canto-Gen IP: you license the audio files, never the voice; never resell or repackage the voices, voice library, or engine as a standalone TTS service. Full terms: Terms of Service v1.2.

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.

1

List the voice catalog (GET /v1/voices)

list voicesbash
curl https://api.canto-gen.com/v1/voices \
  -H "Authorization: Bearer $CANTOGEN_API_KEY"
200 responsejson
{
  "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.

2

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:

202 responsehttp
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

The async endpoint returns 202 with 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.

slugNameGenderAgeScenePreview
keung-gor強哥malemidagenarration
lok-zai樂仔maleadultstory
sung-pak崇伯maleeldernarration
fung-yee鳳儀femaleadultstory
sum-yu芯瑜femaleyoungads
wai小慧femaleadultstory
kay凱琪femaleyoungsports
lok嘉樂maleadultcomedy
sum心妍femaleadultnews
wing-lam-2穎琳femaleadultbusiness
bon阿邦maleadultnarration
ah-sum阿森maleyoungnarration
sze-kei思琪femalemidagenarration
hoi小海maleyoungads
wang-tat宏達maleyoungnarration
wing-wing詠詠femalechildstory
ga-ga嘉嘉femalechildads
siu-laam小藍femalechildstory
siu-mun小滿femalechildeducation
ah-syut阿雪femalechildeducation
ah-him阿謙malechildeducation
ah-hei阿希malechildnarration
siu-yu小宇malechildeducation
so-tai蘇太femaleelderbusiness
ho-je好姐femaleeldercomedy
gan-suk根叔maleelderads
keung-suk強叔maleeldersports
biu-suk標叔maleeldercomedy
jeun-sing晉昇malechildeducation
tin-lok天樂malechildnarration
jyut-cing悅澄femalechildstory
tong-tong糖糖femalechildstory
king-je瓊姐femaleeldercomedy
mei-jan美珍femaleeldernarration
sau-ying秀英femaleelderstory
hiu-cing曉晴femaleteenstory
cin-cin芊芊femaleteensports
wan-ji韻怡femaleteeneducation
jeun-jai俊仔maleteenads
ji-long子朗maleteennarration
hin-jai軒仔maleteencomedy

Generation presets (tempo · emotion · timbre)

Tempo一氣呵成中性自然含糊慵懶大起大落字正腔圓平鋪直敘抑揚起伏擲地有聲輕聲細語邊諗邊講
Emotion冷靜喜悅嘲諷好奇媚惑嫉妒安心寂寞平和心痛悲傷悲愴愉快感慨慈愛憤怒欣喜沮喪溫柔滿足激昂焦躁熱情絕望緊張自豪認真雀躍驚恐驚慌驚訝

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

The three voice modes are mutually exclusive: send exactly one of voice, design, or clone per request — anything else returns 400 voice_mode_conflict. Designed and cloned voices are per-request: they are never saved as reusable voice assets.
voicedefault

Gallery 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.
voice examplebash
# 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 audio

Designed 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.
design examplebash
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 scope

Cloned 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.
clone examplebash
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)

styleDelivery 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.
emotionOne 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.
instructionFree-text delivery direction, up to 500 characters. Priority: style → emotion → instruction — instruction has the final say.
pitchDeprecated (2026-09-20): no-op under raw audio delivery (accepted but ignored). Historical range −12…+12 semitones, default 0.
volumeDeprecated (2026-09-20): no-op under raw audio delivery (accepted but ignored). Historical range 0–10, default 1.
response_formatmp3 (default) / wav.
srttrue → the completed job carries an srt field (billed at a higher character rate). Available on all plans.
happyangrysadsurprisefeardisgustneutralconfusedanxiousaffectionwhisper

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_id
GET /v1/audio/jobs/{id}poll · 2–5 s backoff
status: completedaudio_url ready
GET audio_urlpre-signed · no auth

Poll a job

GET /v1/audio/jobs/{id}bash
curl https://api.canto-gen.com/v1/audio/jobs/b7e6f2a1-4c3d-4e5f-8a9b-0c1d2e3f4a5b \
  -H "Authorization: Bearer $CANTOGEN_API_KEY"

Completed response

completed jobjson
{
  "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 with backoff (Node)js
// 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

audio_url is a pre-signed URL that expires: valid for 1 hour when served from the materialized audio library, and 7 days when served straight from the generation worker. Download promptly and re-poll the job for a fresh URL. audio_url is absent while the job is queued/processing and on failed/cancelled jobs.

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

Billing nuance: account credit for the job includes an SRT surcharge (billedCharacters exceeds base characters when srt: true), while the per-key monthly cap ledger counts the submitted text length flat. Subtitles are available on all plans.

Rate limits & caps

Response headerDescription
X-RateLimit-LimitPer-minute request cap for this key (default 60; configurable at key creation).
X-RateLimit-RemainingRequests left in the current 60-second sliding window.
X-RateLimit-ResetWindow reset time (Unix epoch seconds).
Retry-AfterAttached 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.

transcribe.shbash
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=json

200 response

transcription.jsonjson
{
  "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

Delivery is synchronous — short and medium files (≤8 minutes) return 200 with text directly. Audio over the synchronous delivery cap (480 seconds, C3 2026-10-20) returns 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.

verify-webhook.mjsjs
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"]);
verify_webhook.pypython
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 returns 400 audio_too_long (with duration_seconds + async_endpoint, rejected before processing — nothing billed). Use POST /v1/asr/jobs for 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).

balance.shbash
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

vocabulary-get.shbash
curl https://api.canto-gen.com/v1/asr/vocabulary \
  -H "Authorization: Bearer \$CANTOGEN_API_KEY"
vocabulary.jsonjson
{
  "scope": "api",
  "terms": ["證監會", "庫務局", "Canto-Gen"],
  "updated_at": "2026-10-28T09:12:33.000Z"
}

Replace — PUT /v1/asr/vocabulary

vocabulary-put.shbash
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

vocabulary-delete.shbash
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

The keyword vocabulary feature has to be enabled for the account (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.updateOpenAI-nativeOpen/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.createOpenAI-nativeSend one explicit utterance (input_text); triggers synthesis.
input_text.appendCanto-Gen extensionSend raw token deltas — stream as you generate.
input_text.commitCanto-Gen extensionForce a segment boundary (flush now).
response.createOpenAI-nativeTrigger synthesis.
response.cancelOpenAI-nativeBarge-in: stop the current utterance and refund it.
session.closeCanto-Gen extensionClose the session and settle.

Events — server → client

session.createdOpenAI-nativeSession opened; carries the server-minted session id and the **effective** `max_session_chars` (already clamped to the plan cap).
session.updatedOpenAI-nativeConfig ack.
response.createdOpenAI-nativeAn utterance begins.
response.output_audio.deltaOpenAI-nativeA base64 PCM16 @ 48 kHz audio chunk.
response.output_audio.doneOpenAI-nativeUtterance audio complete.
response.doneOpenAI-nativeUtterance done; usage carries input_chars / billed_chars / remaining (extension fields).
errorOpenAI-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.
Node example clientjs
// 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_key401Key missing, invalid, expired, or wrong scope.
rate_limit_exceeded429Per-user per-minute limit hit (all keys on the account count together); carries retry_after.
sandbox_daily_limit429Free 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_reached429The key's monthly credit cap is reached.
character_limit_reached402Account credit pool exhausted — the utterance is not synthesized.
concurrency_limit_reached429Concurrent session or un-settled utterance cap reached.
session_char_limit_exceeded403This session's character cap is reached.
raw_limit_exceeded413Raw input volume (including punctuation/whitespace) exceeds the cap.
text_too_long400A single utterance exceeds the length limit.
invalid_session400The session is closed or otherwise invalid.
engine_unavailable503The 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.

mint-token.shbash
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

1000completedNormal completion (done received).
1001idle_timeoutNo client frame within 120s.
1008protocol_violationBad protocol / binary frames / invalid base64 / rate exceeded.
1009message_too_bigSingle frame above 640KB.
1011engine_lostEngine disconnected mid-session.
1013engine_unavailableEngine unreachable.
4001invalid_or_expired_tokenKey invalid / expired / revoked.
4002insufficient_balanceBalance below one tick before connect.
4008capacity_exceededConcurrent session cap hit (global 10 / per-key free 2 / paid 4).
4009insufficient_balanceBalance insufficient for the next hold mid-session.
4010invalid_audio_formatContainer file detected (WAV/Ogg/FLAC/MP3) — send raw PCM16LE mono 16 kHz instead.
asr-realtime.jsjs
// 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 envelopejson
{
  "error": "text_too_long",
  "message": "text exceeds 500 characters."
}
HTTPerror codeCauseFix
400invalid_modelmodel must be "cantogen-tts" (or omitted).Omit model or set "cantogen-tts".
400voice_mode_conflictMore than one of voice / design / clone was sent — the three modes are mutually exclusive.Send exactly one voice mode per request.
400text_requiredtext is missing or empty.Include a non-empty text (1–500 characters).
400text_too_longtext exceeds 500 characters.Split the text — over-limit requests are rejected, not truncated.
400unsupported_formatresponse_format must be mp3 or wav.Use mp3 or wav.
400invalid_pitchpitch must be between −12 and +12 semitones.Adjust pitch to the valid range.
400invalid_volumevolume must be between 0 and 10.Adjust volume to the valid range.
400invalid_emotionemotion 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).
400invalid_srtsrt must be a boolean.Use true / false.
400reference_audio_requiredclone.reference_audio is missing.Attach a base64 reference sample.
400invalid_reference_audioclone.reference_audio is not valid base64 audio.Send a data URL (data:audio/…;base64,…) or raw base64.
400invalid_reference_audio_sizeclone.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.
400spoken_text_requiredtext has no speakable content — zero billable credits (only punctuation / whitespace / emoji / tone tags).Include text with readable words.
400design_gender_and_age_requiredBoth design.gender and design.age are required.Provide both fields.
400invalid_job_idThe poll or cancel id is not a UUID.Check the job_id.
400invalid_requestThe 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.
413payload_too_largeThe 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).
401invalid_or_expired_tokenAPI key missing, invalid, expired, or revoked.Create a new key and check the Bearer header.
402character_limit_reachedThe account credit pool cannot cover this generation (the body includes remaining).Buy a credit pack or wait for the monthly reset.
403insufficient_scopeThe key lacks the required scope (cloning needs tts:clone); the body includes "scope".Create a key with the required scope.
403monthly_cap_reachedThe key's monthly credit cap is reached; the body includes "used".Wait for the UTC month to reset or raise the cap.
404job_not_foundNo job with this id (or it belongs to another key).Check the job_id and the key used to submit.
409already_settledThe 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.
409duplicate_requestThe 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.
404not_foundNo such endpoint (typo in the path).Check the paths in /v1/openapi.json.
403batch_requires_proBulk 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.
429capacity_exceededThe public API generation pool is at its global concurrency cap.Wait Retry-After seconds, or use the async `POST /v1/audio/jobs` path.
429rate_limit_exceededPer-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.
503service_unavailableThe 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.
503rate_limit_unavailableThe 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.
429sandbox_daily_limitFree 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.
429api_busyThe API generation queue is at its global capacity cap (rejected before reserve — nothing billed).Wait a few seconds and retry.
502audio_delivery_failedGeneration completed but the audio could not be fetched.Poll GET /v1/audio/jobs/{id} and download the audio_url instead.
503sync_generation_failedThe job failed or was cancelled during the sync wait (already refunded automatically).Retry via POST /v1/audio/jobs (async).
503reference_upload_failedThe clone reference audio could not be stored temporarily.Simply retry.
400unsupported_response_formatTranscription response_format currently supports json / text only — srt / verbose_json need segment-level timestamps and are not yet available.Use json or text.
402insufficient_balanceThe 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).
503engine_unavailableThe 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.
400audio_too_longAudio 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).
400storage_path_session_onlyAn 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.
403storage_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.
404storage_path_not_foundThe 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.
503sync_timeoutThe 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).

generation-jobs.shbash
curl "https://api.canto-gen.com/v1/audio/jobs?limit=20" \
  -H "Authorization: Bearer \$CANTOGEN_API_KEY"
generation-jobs.jsonjson
{
  "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 — the id of the last record on the previous page (a uuid)
  • status — optional filter: queued / processing / cancelling / done / error / cancelled
  • next_before — cursor for the next page; null = no further page
  • text_preview — bounded preview of the generated text (max 120 characters)
  • duration_ms — audio duration in milliseconds (null until 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).

telemetry.shbash
curl https://api.canto-gen.com/v1/account/telemetry \
  -H "Authorization: Bearer \$CANTOGEN_API_KEY"
telemetry.jsonjson
{
  "telemetry_opt_out": false
}
telemetry.shbash
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}'
telemetry-updated.jsonjson
{
  "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).

delete-account.shbash
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"}'
account-deletion.jsonjson
{
  "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

HTTPerrorCause
400invalid_limit`limit` is not an integer between 1 and 100.
400invalid_cursor`before` is not a uuid, or it does not match any of your records.
400invalid_status`status` is outside the allowed set (queued / processing / cancelling / done / error / cancelled).
400invalid_telemetry_opt_out`telemetry_opt_out` is not a boolean.
400confirm_missingThe deletion body is missing `confirmEmail` or `confirmWord`.
400confirm_email_mismatch`confirmEmail` does not match your account email (compared case-insensitively).
400confirm_word_mismatch`confirmWord` is not `DELETE` (case-sensitive).
401invalid_or_expired_tokenAPI key missing, invalid, expired, or revoked.
403insufficient_scopeThe key lacks the `tts:generate` or `tts:design` scope (the generation-record list).
409active_jobsYou still have unfinished generation jobs (queued / processing / cancelling) — wait for them to finish.
409team_ownerYou own a workspace that still has other members — dissolve or hand it over first.
503jobs_unavailableThe generation-record list is temporarily unavailable (`GET /v1/audio/jobs`).
503telemetry_read_failedThe anonymous-usage-stats setting is temporarily unreadable.
503telemetry_update_failedThe anonymous-usage-stats setting could not be saved temporarily.
503deletion_request_failedThe 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

DataRetention / 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 voiceKept 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 deletionDisabled immediately (no further login or API calls), fully purged within 30 days
BackupsEncrypted 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

The text and audio you upload (including reference audio) and the voices derived from them are never used to train, fine-tune or improve our models — in any circumstance. The audio we generate is not used for training either. Improvements come only from the ratings and bug reports you choose to submit.

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).

delete-transcription.shbash
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.

delete-voice.shbash
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.

delete-generation.shbash
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.

POST/v1/audio/speech200 sync

Short-text synchronous generation — 200 audio bytes (voice/design, ≤300 chars).

Full schema → API reference
POST/v1/audio/jobs202 async

Submit 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
GET/v1/audio/jobs/{id}poll

Poll a job; when completed the response carries a pre-signed audio_url.

Full schema → API reference
GET/v1/audio/jobslist

List 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
GET/v1/voices

List the Cantonese-optimized voice catalog, with preview clips. This endpoint allows anonymous access.

Full schema → API reference
DELETE/v1/voices/{id}delete

Delete 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
DELETE/v1/audio/jobs/{id}cancel / delete

A job that is still running is cancelled (refunded); a settled job has its record deleted (job record + audio + subtitle sidecars).

Full schema → API reference
POST/v1/asr/transcribe200 sync

Transcribe 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
POST/v1/asr/jobs202 async

Submit 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
GET/v1/asr/transcriptions/{id}poll

Retrieve a transcription job (queued → processing → completed/failed); completed carries the transcript.

Full schema → API reference
GET/v1/balance

Get the prepaid balance (HKD), transcription/dictation rates and auto top-up settings.

Full schema → API reference
GET/v1/asr/vocabularyread

Read 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
PUT/v1/asr/vocabularyreplace

Replace 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
DELETE/v1/asr/vocabularyclear

Clear 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
GET/v1/account/telemetryread

Read 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
PUT/v1/account/telemetryopt-out

Turn 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
POST/v1/account/deletionirreversible

Delete 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
downloadsbash
# 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.txt

Copy this page as Markdown, or grab the Markdown / llms.txt / OpenAPI machine-readable versions.