End of turn
A voice agent must answer when the caller has finished, not at every pause: “my number is… zero six…” has
pauses, and is not finished. End-of-turn detection listens to how the speaker talks at each pause and sends an
end_of_turn message when their turn is over.
At a glance
Section titled “At a glance”| Live API | end_of_turn |
|---|---|
| Pre-recorded (batch) | Live only |
| Live models | solaria-3 (every live model) |
| Languages | Every language of the model (supported languages) |
Turn it on in the init body:
{ "end_of_turn": true }Then answer when an end_of_turn message arrives. Each program prints the caller’s sentences and each end of turn:
// npm install @gladiaio/sdkimport { readFileSync } from "node:fs";import { GladiaClient } from "@gladiaio/sdk";
const { sampleRate, channels, pcm } = readWav(process.argv[2]); // a 16-bit PCM WAV file
const config = { encoding: "wav/pcm", sample_rate: sampleRate, bit_depth: 16, channels, model: "solaria-3", language_config: { languages: [ "en" ] }, endpointing: 0.3, end_of_turn: { eot_threshold: 0.8, stop_s: 1.2 }, messages_config: { receive_partial_transcripts: true }};
const client = new GladiaClient({ apiKey: process.env.GLADIA_API_KEY, apiUrl: process.env.GLADIA_API_URL ?? "https://eu1.api.gladia.io",});// `end_of_turn` is a Gladia Connect option not in the SDK's types yet: the SDK sends it as is.const session = client.liveV2().startSession(config);
session.on("message", (message) => { if (message.type === "transcript" && message.data.is_final) console.log("caller:", message.data.utterance.text); if (message.type === "end_of_turn") console.log(`end of turn (${message.data.reason}): answer now`);});session.on("error", (error) => { console.error(error); process.exitCode = 1;});session.once("ended", () => process.exit());
const step = (sampleRate * channels * 2) / 10; // 100 ms of audio per chunkfor (let start = 0; start < pcm.length; start += step) { session.sendAudio(pcm.subarray(start, start + step)); // live audio: send each chunk as it is captured}session.stopRecording();
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 };}# pip install -U "gladiaio-sdk>=2.2"import osimport sysimport threadingimport wave
from gladiaio_sdk import GladiaClientfrom gladiaio_sdk.v2.live.generated_types import LiveV2UnknownWebSocketMessage
API_URL = os.environ.get("GLADIA_API_URL", "https://eu1.api.gladia.io")API_KEY = os.environ["GLADIA_API_KEY"]
with wave.open(sys.argv[1]) as wav: # a 16-bit PCM WAV file rate, channels = wav.getframerate(), wav.getnchannels() audio = wav.readframes(wav.getnframes())
config = { "encoding": "wav/pcm", "sample_rate": rate, "bit_depth": 16, "channels": channels, "model": "solaria-3", "language_config": { "languages": [ "en" ] }, "endpointing": 0.3, "end_of_turn": { "eot_threshold": 0.8, "stop_s": 1.2 }}
client = GladiaClient(api_key=API_KEY, api_url=API_URL)# `end_of_turn`: Gladia Connect, not in the SDK's types: a dict is sent as is.session = client.live_v2().start_session(config)ended, errors = threading.Event(), []
@session.on("message")def on_message(message): if message.type == "transcript" and message.data.is_final: print("caller:", message.data.utterance.text) # end_of_turn is not in the SDK's types: it arrives with its raw data if isinstance(message, LiveV2UnknownWebSocketMessage) and message.type == "end_of_turn": print(f"end of turn ({message.data['reason']}): answer now")
session.on("error", errors.append)session.once("ended", lambda _: ended.set())
# Stream once the socket is open: a stop sent while it opens can pass the audio queued until then.connected = threading.Event()session.once("connected", lambda _: connected.set())session.once("ended", lambda _: connected.set()) # a session that never connects endssession.on("error", lambda _: connected.set())if session.status == "connected": # it opened before the listener above connected.set()if not connected.wait(timeout=30) or errors or ended.is_set(): sys.exit(1) # no open session to stream to
step = rate * channels * 2 // 10 # 100 ms of audio per chunkfor start in range(0, len(audio), step): session.send_audio(audio[start : start + step]) # live audio: send each chunk as it is capturedsession.stop_recording()
ended.wait(timeout=60)sys.exit(1 if errors or not ended.is_set() else 0)Create the session, then stream its audio to the returned url (Live WebSocket):
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, "model": "solaria-3", "language_config": { "languages": [ "en" ] }, "endpointing": 0.3, "end_of_turn": { "eot_threshold": 0.8, "stop_s": 1.2 } }'The message:
{ "type": "end_of_turn", "session_id": "0199d7a2-5c3e-7b41-9f0a-3c2d1e4f5a6b", "data": { "channel": 0, "probability": 0.97, "reason": "model", "end": 18.42, "speech_duration": 3.1 }}reason is model when the probability that the speaker finished crossed eot_threshold, or timeout when the
silence reached stop_s whatever the probability.
Options
Section titled “Options”"end_of_turn": true uses the defaults, and so does an empty object ("end_of_turn": {}); an object turns it on and changes some of them. Omitted or false: off. An unknown option or a value out of its range is a 400 that names it.
{ "end_of_turn": { "eot_threshold": 0.8, "stop_s": 1.2 } }| option | range | what it does |
|---|---|---|
eot_threshold |
0 to 1 (excluded) | Probability above which the turn ends. Lower: faster answers, more interruptions. |
silence_ms |
1 to 10000 | Silence, in ms, before a pause is evaluated: every pause of the turn, also the ones after the speaker went on. |
stop_s |
up to 60 | Silence, in seconds, that ends the turn anyway. |
emit_scores |
Also send end_of_turn_score for each evaluation, to calibrate eot_threshold. |
|
min_end_of_turn_silence_when_confident |
0 to 5000 | Silence, in ms, that must follow a turn judged complete before the end of turn is sent; speech meanwhile cancels it. 0: as soon as the model is sure. |
speculation |
true, or { threshold } |
Compare each final to the text of the end_of_turn and send a speculation verdict (below). Off when omitted. |
window_s |
up to 8 | Audio, in seconds, an evaluation reads. |
reeval_ms |
0 to 10000 | Interval between two evaluations of the same pause. |
eager_eot_threshold |
0 to 1 (excluded), at most eot_threshold |
Send an eager_end_of_turn from this probability, before the turn is confirmed (below). Off when omitted. |
threshold and confirm_ms, the first names of eot_threshold and min_end_of_turn_silence_when_confident, still work but are deprecated: send the new names. They are refused from January 31, 2027.
GET /v2/live/defaults returns the defaults in force.
Eager end of turn
Section titled “Eager end of turn”A voice agent that waits for end_of_turn before calling its LLM adds the LLM’s whole latency after the caller
stopped. With eager_eot_threshold, the engine also tells you when the turn is probably over, so the LLM can
start early:
{ "end_of_turn": { "eot_threshold": 0.9, "eager_eot_threshold": 0.6 } }At a pause whose probability reaches eager_eot_threshold, an eager_end_of_turn arrives:
{ "type": "eager_end_of_turn", "session_id": "0199d7a2-5c3e-7b41-9f0a-3c2d1e4f5a6b", "data": { "channel": 0, "probability": 0.72, "end": 4.18, "speech_duration": 3.2 }}Then exactly one of:
end_of_turn: the turn is confirmed. Send the answer you prepared.turn_resumed: the caller spoke again. Drop the answer you prepared, and keep listening:
{ "type": "turn_resumed", "session_id": "0199d7a2-5c3e-7b41-9f0a-3c2d1e4f5a6b", "data": { "channel": 0, "end": 4.62 }}end is where the caller started speaking again. A resumed turn can bring a new eager_end_of_turn at its next
pause.
- It costs LLM calls. Each
turn_resumedthrows away an answer you paid for. The lowereager_eot_threshold, the earlier the eager, and the more resumes. Values from 0.3 to 0.9 work; turn onemit_scoreson real calls and pick one under the probabilities of your callers’ mid-sentence pauses. - Send
eot_thresholdwith it.eager_eot_thresholdaboveeot_thresholdis a 400 on the init. Withouteot_threshold, the server’s default applies (GET /v2/live/defaults), and an eager threshold above it is a 400 too. - No final at eager time. Build the LLM’s prompt from the partial transcripts; the final comes after
end_of_turn, as without the eager. - No eager during a
hold. While the caller dictates a phone number, an address or an amount, no eager is sent. - An eager can end without a confirmation. If the session ends (
end_session) while an eager is open, neitherend_of_turnnorturn_resumedis sent: drop the answer you prepared. - An
end_of_turnwithreason: modelalways follows an eager, sent just before it when none came at the pause. Areason: timeoutend of turn can come without one.
Speculative LLM turn
Section titled “Speculative LLM turn”Starting the LLM on eager_end_of_turn or end_of_turn answers earlier, but the call starts on the text the
engine had at the pause. The final that closes the turn comes later, and it can differ: a last word that
arrives late, a number written another way, or a caller who went on talking. With speculation, you are told
whether the call you started on that text is still good, so you recompute only when needed.
{ "end_of_turn": { "speculation": true } }For each turn, three messages arrive, in this order:
end_of_turn, withtext: the text to start the LLM call on.
With an eager threshold, eager_end_of_turn carries a text too. The final is compared to the text of the first message of the pause, so start the call on that one. The end_of_turn that confirms it may show a newer text; the call you started stays valid if the verdict says keep.
{ "type": "end_of_turn", "session_id": "0199d7a2-5c3e-7b41-9f0a-3c2d1e4f5a6b", "data": { "channel": 0, "probability": 0.97, "reason": "model", "end": 4.18, "speech_duration": 3.2, "text": "book a table for two" }}- The
finalof the turn. Itsutterance.speculationholds the verdict, the same as the message below. speculation, after the final (and after the other add-on messages of that final, if you enabled any), on akeeptoo:
{ "type": "speculation", "session_id": "0199d7a2-5c3e-7b41-9f0a-3c2d1e4f5a6b", "created_at": "2026-10-17T10:00:00.000Z", "error": null, "data": { "utterance_id": "00_00000003", "utterance": { "text": "Book a table for two.", "start": 1.0, "end": 4.0, "language": "en", "confidence": 0.9, "channel": 0, "words": [] }, "results": [ { "eager_text": "book a table for two", "eager_end": 4.18, "similarity": 1.0, "lexical_similarity": 1.0, "recommendation": "keep", "reason": "same_text" } ] }}recommendation is keep when similarity reaches the threshold, discard otherwise. reason is same_text,
similar, text_changed or caller_went_on. The program below starts a fake LLM call (a timer standing in for
your model) on end_of_turn, keeps it on keep, and restarts it on the final on a discard:
// npm install @gladiaio/sdkimport { readFileSync } from "node:fs";import { GladiaClient } from "@gladiaio/sdk";
const { sampleRate, channels, pcm } = readWav(process.argv[2]); // a 16-bit PCM WAV file
const config = { encoding: "wav/pcm", sample_rate: sampleRate, bit_depth: 16, channels, model: "solaria-3", language_config: { languages: ["en"] }, endpointing: 0.3, end_of_turn: { speculation: true, stop_s: 1.2 }, messages_config: { receive_realtime_processing_events: true },};
// Stands in for your LLM call: it answers after 300 ms unless it is cancelled.function startLlm(prompt) { const call = { prompt }; call.reply = new Promise((resolve) => { const timer = setTimeout(() => resolve(`(answer to: ${prompt})`), 300); call.cancel = () => { clearTimeout(timer); resolve(null); }; }); call.reply.then((reply) => reply && console.log("agent:", reply)); return call;}
const client = new GladiaClient({ apiKey: process.env.GLADIA_API_KEY, apiUrl: process.env.GLADIA_API_URL ?? "https://eu1.api.gladia.io",});// `end_of_turn` is a Gladia Connect option not in the SDK's types yet: the SDK sends it as is.const session = client.liveV2().startSession(config);
let call = null; // the LLM call started on the last end of turnlet judged = false; // the verdict of the last end of turn camelet settle; // resolves `verdict`let verdict = new Promise((resolve) => (settle = resolve)); // pending until a verdict comeslet final = ""; // the last final of the caller
session.on("message", (message) => { if (message.type === "end_of_turn") { call?.cancel(); // a new end of turn replaces the call of the previous one const text = message.data.text ?? ""; call = text ? startLlm(text) : null; // no text, no call, and no verdict will follow if (text && judged) { judged = false; // a verdict is coming for this turn verdict = new Promise((resolve) => (settle = resolve)); } console.log(`end of turn: LLM started on "${text}"`); } if (message.type === "turn_resumed") { call?.cancel(); // the caller went on: drop the call, no verdict follows call = null; judged = true; settle(); } if (message.type === "transcript" && message.data.is_final) { final = message.data.utterance.text; console.log("caller:", final); } if (message.type === "speculation") { judged = true; settle(); const result = message.data.results[0]; if (result.recommendation === "keep") { console.log(`KEEP ${result.similarity}`); } else { console.log(`DISCARD ${result.reason}`); call?.cancel(); // `caller_went_on`: the turn was not over, wait for the next end_of_turn call = result.reason === "caller_went_on" ? null : startLlm(final); } }});session.on("error", (error) => { console.error(error); process.exitCode = 1;});session.once("ended", async () => { await call?.reply; // let the last answer print process.exit();});
const step = (sampleRate * channels * 2) / 10; // 100 ms of audio per chunkfor (let start = 0; start < pcm.length; start += step) { session.sendAudio(pcm.subarray(start, start + step)); // live audio: send each chunk as it is captured await new Promise((resolve) => setTimeout(resolve, 100)); // at the speed of speech, as a microphone would}// A live agent keeps the line open. This file is over: wait for the verdict before stopping, or the// stop closes the turn before the engine has judged the pause (10 s at most, the file needs// trailing silence for the engine to end the turn).await Promise.race([verdict, new Promise((resolve) => setTimeout(resolve, 10_000))]);session.stopRecording();
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 };}# pip install -U "gladiaio-sdk>=2.2"import osimport sysimport threadingimport timeimport wave
from gladiaio_sdk import GladiaClientfrom gladiaio_sdk.v2.live.generated_types import LiveV2UnknownWebSocketMessage
API_URL = os.environ.get("GLADIA_API_URL", "https://eu1.api.gladia.io")API_KEY = os.environ["GLADIA_API_KEY"]
with wave.open(sys.argv[1]) as wav: # a 16-bit PCM WAV file rate, channels = wav.getframerate(), wav.getnchannels() audio = wav.readframes(wav.getnframes())
config = { "encoding": "wav/pcm", "sample_rate": rate, "bit_depth": 16, "channels": channels, "model": "solaria-3", "language_config": {"languages": ["en"]}, "endpointing": 0.3, "end_of_turn": {"speculation": True, "stop_s": 1.2}, "messages_config": {"receive_realtime_processing_events": True},}
class FakeLlm: """Stands in for your LLM call: it answers after 300 ms unless it is cancelled."""
def __init__(self, prompt): self.prompt = prompt self.done = threading.Event() self.timer = threading.Timer(0.3, self._answer) self.timer.start()
def _answer(self): print("agent:", f"(answer to: {self.prompt})", flush=True) self.done.set()
def cancel(self): self.timer.cancel() self.done.set()
client = GladiaClient(api_key=API_KEY, api_url=API_URL)# `end_of_turn`: Gladia Connect, not in the SDK's types: a dict is sent as is.session = client.live_v2().start_session(config)ended, judged, errors = threading.Event(), threading.Event(), []call = None # the LLM call started on the last end of turnfinal = "" # the last final of the caller
@session.on("message")def on_message(message): global call, final # end_of_turn and speculation are not in the SDK's types: they arrive with their raw data unknown = isinstance(message, LiveV2UnknownWebSocketMessage) if unknown and message.type == "end_of_turn": if call: call.cancel() # a new end of turn replaces the call of the previous one text = message.data.get("text") or "" call = FakeLlm(text) if text else None # no text, no call, and no verdict will follow if text: judged.clear() # a verdict is coming for this turn print(f'end of turn: LLM started on "{text}"', flush=True) if message.type == "turn_resumed": # the caller went on: drop the call, no verdict follows if call: call.cancel() call = None judged.set() if message.type == "transcript" and message.data.is_final: final = message.data.utterance.text print("caller:", final, flush=True) if unknown and message.type == "speculation": judged.set() verdict = message.data["results"][0] if verdict["recommendation"] == "keep": print("KEEP", verdict["similarity"], flush=True) else: print("DISCARD", verdict["reason"], flush=True) if call: call.cancel() # `caller_went_on`: the turn was not over, wait for the next end_of_turn call = None if verdict["reason"] == "caller_went_on" else FakeLlm(final)
session.on("error", errors.append)session.once("ended", lambda _: ended.set())
# Stream once the socket is open: a stop sent while it opens can pass the audio queued until then.connected = threading.Event()session.once("connected", lambda _: connected.set())session.once("ended", lambda _: connected.set()) # a session that never connects endssession.on("error", lambda _: connected.set())if session.status == "connected": # it opened before the listener above connected.set()if not connected.wait(timeout=30) or errors or ended.is_set(): sys.exit(1) # no open session to stream to
step = rate * channels * 2 // 10 # 100 ms of audio per chunkfor start in range(0, len(audio), step): session.send_audio(audio[start : start + step]) # live audio: send each chunk as it is captured time.sleep(0.1) # at the speed of speech, as a microphone would# A live agent keeps the line open. This file is over: wait for the verdict before stopping, or the# stop closes the turn before the engine has judged the pause (10 s at most, the file needs# trailing silence for the engine to end the turn).judged.wait(timeout=10)session.stop_recording()
ended.wait(timeout=60)if call: call.done.wait(timeout=5) # let the last answer printsys.exit(1 if errors or not ended.is_set() else 0)- A
discardwithcaller_went_onmeans the turn was not over. The caller spoke again after theend_of_turn: cancel the call and wait for the nextend_of_turn, do not restart on this final. - The message comes on a
keeptoo.similarityis useful on its own to see how often the pause text and the final agree on your calls. - A turn can end without a verdict. No
speculationmessage comes when theend_of_turnhas an emptytext(the engine had nothing to start on: do not start a call), or when aturn_resumedfollows (the caller went on: cancel the call). A newend_of_turnalso replaces the call of the previous one: cancel it first, as the program does. - The block can grow. The engine may add fields to the block and values to
reason. Readrecommendationto decide, and treatreasonand any other field as information, not as a closed list. thresholdis a trade-off.{ "speculation": { "threshold": 0.9 } }: higher recomputes more often and answers the wrong thing less often; lower keeps more calls and risks answering on a stale text. Watchsimilarityon real calls before you change it.- Callbacks get
speculation, notend_of_turn. Thespeculationmessage follows the otherreceive_realtime_processing_eventsmessages on the callback;end_of_turnstays on the WebSocket.
Building a voice agent
Section titled “Building a voice agent”- Use a low-latency model and profile:
solaria-3-fast. - Turn on partial transcripts to prepare the answer while the caller speaks.
- Answer on
end_of_turn, with the finals received so far. - If the caller speaks again before you answer, cancel and wait for the next
end_of_turn.
Limits and gotchas
Section titled “Limits and gotchas”- Off unless you ask. A session without
end_of_turngets no end-of-turn message. - WebSocket only.
end_of_turnmessages are never sent to callbacks: the agent that answers must hold the WebSocket. - Per channel. Each channel has its own turns: with the caller and the agent on two channels, read
channel. eot_thresholdis a trade-off. Lower answers sooner and interrupts more; higher waits for clearer endings. Turn onemit_scoreson real calls to see the probabilities, then set it.stop_sis your ceiling. Whatever the probability, a silence that long ends the turn (reason: timeout): keep it under what your callers will tolerate.- Endpointing still applies. Finals still come on each pause: buffer them, answer on
end_of_turn. Thefinalsoption picks whether the end of the turn, the end of a sentence or the pause alone closes a final. - Python SDK: see above, use a raw WebSocket or the JavaScript SDK.
- Eager end of turn is opt-in. Without
eager_eot_threshold, noeager_end_of_turnorturn_resumedis sent.