Skip to main content

Stream LLM responses to speech

Connect an LLM to TTS via streaming to build a voice agent that responds as quickly as in a real conversation. You can achieve a TTFA (time until audio playback starts) of under one second, suitable for character chat, voice agents, and similar applications.

Open a Kitsch Labs TTS WebSocket as you start the LLM request. Forward text deltas as they arrive.

Stream the reply​

Start sending and receiving together​

Open the TTS WebSocket and start the LLM request concurrently. These snippets show the core flow. In JavaScript, the tasks share an abort signal, and playbackDone waits for ffplay to exit.

async def speak(llm, model, messages, api_key, voice_id, player):
socket_ready = asyncio.get_running_loop().create_future()
async with asyncio.TaskGroup() as group:
group.create_task(receive_audio(api_key, voice_id, socket_ready, player))
group.create_task(send_text(llm, model, messages, socket_ready))
await player.drain()

Forward text deltas as they arrive​

Send each non-empty delta on the same WebSocket and preserve whitespace. Send flush once when the LLM stream ends.

async def send_text(llm, model, messages, socket_ready):
stream = await llm.chat.completions.create(
model=model, messages=messages, stream=True
)
async with stream:
ws = await socket_ready
async for chunk in stream:
if chunk.choices and (delta := chunk.choices[0].delta.content):
await ws.send(json.dumps({"text": delta}))
await ws.send(json.dumps({"flush": True}))

Play PCM as it arrives​

Play 24 kHz mono PCM16 in arrival order. The isFinal event marks the end of audio delivery. The full examples wait for playback to finish.

async def receive_audio(api_key, voice_id, socket_ready, player):
url = (
"wss://api.kitschlabs.com/v1/text-to-speech/"
f"{quote(voice_id, safe='')}/stream-input"
"?output_format=pcm_24000&language_code=en"
)
async with connect(url, additional_headers={"xi-api-key": api_key}) as ws:
await ws.send(json.dumps({"text": " "}))
socket_ready.set_result(ws)
while True:
event = json.loads(await ws.recv())
if "error" in event:
raise RuntimeError("Kitsch TTS returned an error.")
if audio := event.get("audio"):
await player.write(base64.b64decode(audio, validate=True))
if event.get("isFinal") is True:
return

Measure first playback​

TTFA in this guide runs from the first LLM text delta to the start of audio playback with the TTS connection already open.

The Python example reports three intervals. Playback timing estimates when the output device starts playing the first non-silent sample.

IntervalIncludes
LLM request start → first text deltaTime until the LLM returns text.
First text delta → first PCMTTS connection wait, if any, text delivery, and time until audio arrives.
First PCM → first device outputAudio buffering and estimated device output delay.

The JavaScript example reports the time from the LLM request to the first delta and from the first delta to the first PCM.

To compare configurations, replay the same deltas with the same arrival intervals. Report p50 and p95 for each interval among completed requests and count failures separately.

Run the example​

Each example sends one prompt to an English tutor and plays the reply.

  1. Choose a language and install its dependencies.

    Use Python 3.11 or later and an output device that supports 24 kHz mono. On Linux, you may need to install PortAudio first. sounddevice installation

    python -m pip install 'websockets>=14,<17' 'sounddevice>=0.5,<0.6' 'openai>=2,<3'
  2. Set the following environment variables in the process that runs the example. Keep API keys on the server in a deployed application.

    VariableValue
    KITSCH_API_KEYYour Kitsch Labs API key.
    KITSCH_VOICE_IDThe ID of a voice that supports English from GET /v1/voices.
    LLM_BASE_URLThe base URL of your Chat Completions-compatible API.
    LLM_API_KEYThe API key for that LLM API.
    LLM_MODELA model that supports streaming text responses on that API.
  3. Download the full example below and run it with a text prompt. Press Ctrl+C to cancel both streams and stop playback.

    python voice_conversation.py "What was the best part of your day?"
Download the full Python example Download the full JavaScript example