Skip to Content

Text to speech

Generate speech over HTTP for one-shot work, or keep a WebSocket open for a live stream.

Choose a published TTS model with GET /v1/inference/models, then discover its approved voices with GET /v1/inference/voices?model=MODEL. Send the public model name and the returned voice UUID for one-shot speech, or keep a live session open for a stream of utterances.

Generate speech over HTTP

POST /v1/inference/audio/speech
Authorization: Bearer INFERENCE_API_KEY
Content-Type: application/json
Idempotency-Key: unique-computation-id

{
  "model": "kejue-tts",
  "voice": "VOICE_UUID_FROM_THE_CATALOG",
  "input": "Welcome to Kejue."
}

kejue-tts is the published text-to-speech name today. Names are per workspace, so confirm yours with GET /v1/inference/models rather than hard-coding this one. An unknown or unpublished name, or a speech-to-text name, returns 404 inference_model_not_found. A voice that is not approved for the model returns 404 inference_voice_not_found. Text is bounded to 8,000 Unicode characters and 32,000 UTF-8 bytes.

Text to speech is charged by input length, in Unicode characters of input as you send it. The whole input is reserved up front (402 inference_quota_exhausted if your balance is short) and charged once audio starts; nothing is charged if no audio is produced. How long the speech is never changes the charge. The response header X-Kejue-Characters carries the characters charged. See Usage and limits.

max_audio_seconds (1–600) is optional. It only caps how much audio one request may produce, as a safety limit; the published model also has its own audio limit. It does not change what you are charged.

The success body is raw little-endian PCM16, mono, 16 kHz (audio/pcm), without a WAV header. X-Kejue-Sample-Rate gives the rate; X-Kejue-Characters gives the characters charged; X-Kejue-Request-Id identifies the durable usage record and is also returned on errors after admission and on repeated request identities. Start playback as chunks arrive. Add a WAV header before saving a playable WAV file.

Confirm completion

A 200 and an EOF alone do not prove that generation completed: the model or connection can fail after audio begins. Clients that support HTTP trailers can read X-Kejue-Inference-Status: completed, error, or cancelled. Browsers cannot read trailers, so use GET /v1/inference/requests/{id} after consuming the body and inspect status and error_code. output_limit means output stopped at the audio cap: the generated portion reached its limit. The input is still charged in full.

A repeated Idempotency-Key returns 409 inference_request_exists; it never starts a second generation, even if you change the input. We do not store audio for replay. If you lose the connection, inspect the request before choosing to start a new computation with a new key.

Live speech (WebSocket)

Keep a session open when text arrives in pieces, such as LLM output. Each utterance reuses the connection instead of paying setup time again. Use POST /v1/inference/audio/speech when you already have the whole text.

Connect your backend directly to GET /v1/inference/audio/speech/realtime. Send your Inference key in the Authorization: Bearer … handshake header, and model, voice, and optionally max_characters and max_audio_seconds in the query string. You do not need to mint a token first. Install the Python client with pip install "websockets>=14".

  1. Open the socket with a published TTS model and approved voice UUID. max_characters (1–100,000, default 10,000) is the session's character budget, reserved at connect and clamped to your balance. max_audio_seconds (1–600, default 600) only caps the speech the session may produce. TTS takes no language; the voice decides it.
  2. Wait for {"type":"ready","request_id":"…","sample_rate":16000}.
  3. Send {"type":"speak","text":"…"} for each utterance (1–8,000 characters). You can send the next one before the previous finishes; we speak them in order.
  4. Audio arrives as binary frames of little-endian PCM16 mono at the ready event's sample_rate. After each utterance we send {"type":"done","segment":0,"audio_ms":1840}. Segments count from 0 in the order you sent them.
  5. Send {"type":"finish"} when you are done. We speak everything queued, send {"type":"finished"}, and close with 1000.
Client messageEffect
{"type":"speak","text":"…"}Queue an utterance
{"type":"cancel"}Drop every utterance not yet fully spoken; we answer {"type":"cancelled","segments":[…]} with the dropped segments
{"type":"keepalive"}Hold a quiet session open
{"type":"finish"}End once the queue drains; we answer {"type":"finished"}
import asyncio, json, os

from urllib.parse import urlencode

from websockets.asyncio.client import connect

API = os.environ.get("KEJUE_API_BASE", "https://api.kejue.co/v1")
KEY = os.environ["KEJUE_INFERENCE_KEY"]


async def main() -> None:
    query = urlencode({
        "model": "kejue-tts",
        "voice": "VOICE_UUID_FROM_THE_CATALOG",
    })
    socket_base = API.replace("https://", "wss://", 1).replace("http://", "ws://", 1)
    url = f"{socket_base}/inference/audio/speech/realtime?{query}"
    async with connect(url, additional_headers={"Authorization": f"Bearer {KEY}"}) as ws:
        ready = json.loads(await ws.recv())
        if ready["type"] != "ready":
            raise RuntimeError(ready)
        print("sample rate", ready["sample_rate"])
        await ws.send(json.dumps({"type": "speak", "text": "Welcome to Kejue."}))
        await ws.send(json.dumps({"type": "speak", "text": "How can I help today?"}))
        await ws.send(json.dumps({"type": "finish"}))

        finished = False
        with open("speech.pcm", "wb") as audio:
            async for message in ws:
                if isinstance(message, bytes):
                    audio.write(message)
                    continue
                event = json.loads(message)
                if event["type"] == "done":
                    print("segment", event["segment"], event["audio_ms"], "ms")
                elif event["type"] == "error":
                    raise RuntimeError(event["code"])
                elif event["type"] == "finished":
                    finished = True
                    break
        if not finished:
            raise RuntimeError("Session closed before finished; output may be incomplete")


asyncio.run(main())

speech.pcm is headerless PCM; add a WAV header at the ready event's sample rate to play it. Use request_id from the ready event with GET /v1/inference/requests/{id} to inspect the session afterwards.

Each speak message is charged by its characters when we accept it, against the session's max_characters budget. A message that would pass the budget is refused with {"type":"error","code":"character_limit_reached"} and costs nothing. Unused budget is released when the session ends. A session lasts at most 9 minutes. If nothing is queued and we receive nothing for 60 seconds, we send {"type":"error","code":"idle_timeout"} and close; send keepalive to hold a quiet session open.

Close codeMeaning
1000Normal close after finished
1008idle_timeout, audio_limit_reached, character_limit_reached, or invalid_message (preceded by an error event)
1011The model failed

Live sessions need inference-tts:create.

Connect from a browser

Keep your long-lived key on your backend. Call POST /v1/inference/realtime-tokens there with model, voice, and optionally max_characters and max_audio_seconds, then return the response to your authenticated frontend. It contains kind: "tts", an absolute WebSocket url, and a one-use token valid for 30 seconds. Connect to url with ?token=TOKEN and use the same session messages above. Do not send an Authorization header or configuration parameters with a token.

A token is consumed on the first connection attempt, including a failed attempt; request a fresh one before reconnecting. See WebSocket authentication.

Voice samples

GET /v1/inference/voices/{id}/sample?model=MODEL returns a cached WAV sample when sample_available is true. Both voice endpoints require model; omitting it returns 422. Playback does not invoke the model or debit customer credit. A sample is available only when it has been published for that model and voice. A missing sample returns 404 not_found.

On this page