Keep a live transcription session open during silence (keep-alive)
The problem. A live session stops after 60 seconds without audio. Most of the time that is what you want: a client that went away should not hold a session. But some pauses are part of the conversation: a contact-center agent puts the caller on hold for three minutes, a meeting participant mutes their microphone, a voice agent stops streaming the user’s microphone while it speaks. When the audio comes back, the session is gone and you must create a new one, losing its context and its transcript continuity.
The fix. While you send no audio, send this message every few seconds on the WebSocket:
{ "type": "keep_alive" }The session stays open and its transcription engine stays ready for you, so the first words after the pause
are transcribed with no delay. It is the same as Deepgram’s KeepAlive.
At a glance
Section titled “At a glance”| Live API | keep_alive (client message) |
|---|---|
| Pre-recorded (batch) | Live only |
| Live models | solaria-3, trantoria-1 (every live model) |
| Languages | Every language of the model (supported languages) |
Step by step
Section titled “Step by step”1. Stop the audio, start the keep_alive timer
Section titled “1. Stop the audio, start the keep_alive timer”When the pause starts (the hold button, the mute button, your agent starts speaking), stop sending audio and send
keep_alive every 5 to 30 seconds. The server does not answer it.
2. Stop the timer when the audio comes back
Section titled “2. Stop the timer when the audio comes back”Send the audio again as usual, and stop sending keep_alive. The transcripts go on in the same session: the
utterances keep their order and their timestamps follow the audio you sent, not the clock (a 3-minute hold does not
shift them by 3 minutes).
Each program below streams the first half of a 16-bit WAV file like a microphone, puts the call on hold for
HOLD_S seconds (10 by default) with keep_alive, then streams the second half in the same session. Put your API
key in the GLADIA_API_KEY environment variable, then run HOLD_S=180 python keep_alive.py call.wav (or
HOLD_S=180 node keep_alive.mjs call.wav).
# pip install requests websocketsimport asyncioimport jsonimport osimport sysimport wave
import requestsimport websockets
API_URL = os.environ.get("GLADIA_API_URL", "https://eu1.api.gladia.io")HOLD_S = float(os.environ.get("HOLD_S", "10")) # how long the call stays on holdKEEP_ALIVE_EVERY_S = 5.0 # well under the 60 seconds after which a silent session stops
async def print_finals(ws: websockets.ClientConnection) -> None: async for raw in ws: # until the server closes the connection message = json.loads(raw) if message["type"] == "transcript" and message["data"]["is_final"]: print("final:", message["data"]["utterance"]["text"])
async def main(path: str) -> None: with wave.open(path) as wav: # a 16-bit PCM WAV file rate, channels = wav.getframerate(), wav.getnchannels() audio = wav.readframes(wav.getnframes()) created = requests.post( f"{API_URL}/v2/live", headers={"x-gladia-key": os.environ["GLADIA_API_KEY"]}, json={"encoding": "wav/pcm", "sample_rate": rate, "bit_depth": 16, "channels": channels}, timeout=10, ) created.raise_for_status()
async with websockets.connect(created.json()["url"]) as ws: reader = asyncio.create_task(print_finals(ws)) step = rate * channels * 2 // 10 # 100 ms of audio per chunk half = len(audio) // 2 // (channels * 2) * (channels * 2) # a whole number of samples
async def stream(part: bytes) -> None: for start in range(0, len(part), step): await ws.send(part[start : start + step]) # live audio: each chunk as captured
await stream(audio[:half]) print(f"on hold for {HOLD_S:.0f} s") held = 0.0 while held < HOLD_S: # no audio: keep the session open await ws.send(json.dumps({"type": "keep_alive"})) wait = min(KEEP_ALIVE_EVERY_S, HOLD_S - held) await asyncio.sleep(wait) held += wait print("back from hold") await stream(audio[half:]) await ws.send(json.dumps({"type": "stop_recording"})) await reader # the last finals, then the server closes the connection
asyncio.run(main(sys.argv[1]))// Node.js 22 or later: fetch and WebSocket are built inimport { readFileSync } from "node:fs";import { setTimeout as sleep } from "node:timers/promises";
const API_URL = process.env.GLADIA_API_URL ?? "https://eu1.api.gladia.io";const HOLD_S = Number(process.env.HOLD_S ?? 10); // how long the call stays on holdconst KEEP_ALIVE_EVERY_S = 5; // well under the 60 seconds after which a silent session stopsconst { sampleRate, channels, pcm } = readWav(process.argv[2]); // a 16-bit PCM WAV file
const created = await fetch(`${API_URL}/v2/live`, { method: "POST", headers: { "x-gladia-key": process.env.GLADIA_API_KEY, "content-type": "application/json" }, body: JSON.stringify({ encoding: "wav/pcm", sample_rate: sampleRate, bit_depth: 16, channels }),});if (!created.ok) throw new Error(`${created.status} ${await created.text()}`);
const ws = new WebSocket((await created.json()).url);ws.addEventListener("message", ({ data }) => { const message = JSON.parse(data); if (message.type === "transcript" && message.data.is_final) console.log("final:", message.data.utterance.text);});ws.addEventListener("error", () => { console.error("the WebSocket failed"); process.exitCode = 1;});await new Promise((resolve) => ws.addEventListener("open", resolve, { once: true }));
const step = (sampleRate * channels * 2) / 10; // 100 ms of audio per chunkconst half = Math.floor(pcm.length / 2 / (channels * 2)) * (channels * 2); // a whole number of samplesconst stream = (part) => { for (let start = 0; start < part.length; start += step) { ws.send(part.subarray(start, start + step)); // live audio: each chunk as captured }};
stream(pcm.subarray(0, half));console.log(`on hold for ${HOLD_S} s`);for (let held = 0; held < HOLD_S; ) { // no audio: keep the session open ws.send(JSON.stringify({ type: "keep_alive" })); const wait = Math.min(KEEP_ALIVE_EVERY_S, HOLD_S - held); await sleep(wait * 1000); held += wait;}console.log("back from hold");stream(pcm.subarray(half));ws.send(JSON.stringify({ type: "stop_recording" })); // the last finals, then the server closes the connection
function readWav(path) { const file = readFileSync(path); let fmt, pcm; for (let pos = 12; pos < file.length; ) { const id = file.toString("ascii", pos, pos + 4); const size = file.readUInt32LE(pos + 4); if (id === "fmt ") fmt = { channels: file.readUInt16LE(pos + 10), sampleRate: file.readUInt32LE(pos + 12) }; if (id === "data") pcm = file.subarray(pos + 8, pos + 8 + size); pos += 8 + size + (size % 2); } return { ...fmt, pcm };}Create the session and stream its audio to the returned url (Live WebSocket).
While no audio flows, send {"type": "keep_alive"} on it as a text frame every 5 to 30 seconds:
curl -X POST https://eu1.api.gladia.io/v2/live \ -H "x-gladia-key: $GLADIA_API_KEY" \ -H "content-type: application/json" \ -d '{ "encoding": "wav/pcm", "sample_rate": 16000, "bit_depth": 16, "channels": 1 }'final: Hello, I'd like to change my delivery address.on hold for 180 sback from holdfinal: Yes, I'm still here. It's 12 Baker Street.Limits and gotchas
Section titled “Limits and gotchas”- Billed as session time. A pause held with
keep_aliveis billed like the audio it replaces, from the end of your audio until the audio comes back or you sendstop_recording: the transcription engine stays reserved for your session. A pause withoutkeep_alive(under 60 seconds) is not billed, and neither is the wait of a session that stops for lack of audio andkeep_alive. - An hour at most by default. A session held with
keep_alivestops once it has received no audio for an hour (your administrator may set another value), as if you sentstop_recording: its final transcript is kept. It also stops at its maximum duration, pauses included. - Send it more often than every 60 seconds. The session stops 60 seconds after the last audio or the last
keep_alive. Every 5 to 30 seconds leaves room for a slow network. - Not while you stream audio. The audio itself keeps the session open:
keep_aliveis for the pauses. Akeep_alivesent while the audio flows changes nothing and is not billed twice. - A text frame. Send
{"type": "keep_alive"}as a text WebSocket message: a binary frame is read as audio. - Never answered. The server sends nothing back. To know the session is still open, watch the connection: it stays open.
- Silence works too, at the same price. Streaming silent audio also keeps a session open;
keep_alivecosts you no bandwidth. - Not with Gladia’s cloud API.
keep_aliveis a Gladia Enterprise message: the cloud API ignores it.
Troubleshooting
Section titled “Troubleshooting”| symptom | cause | fix |
|---|---|---|
| the session ends 60 s into the pause | keep_alive sent as a binary frame, with another type (KeepAlive), or less often than every 60 s |
send {"type": "keep_alive"} as a text frame, every 5 to 30 s |
the session ends after a long hold, end_session with the final transcript |
the pause reached the longest one allowed (an hour by default) | resume the audio sooner, or ask your administrator for a longer pause |