Skip to content
IntroducingSPEV, the first audio-in decision modelRead the launch →
SPEV, the first audio-in decision model →
sprag

Turn detection over a WebSocket

Stream a caller's audio over one WebSocket and receive an event when their turn starts, pauses, and ends.

The turns WebSocket lets you stream a caller's audio and receive an event at each turn boundary. The server reads every pause as it happens, so your code does not choose when to ask for a decision.

Detect a turn

This script streams a file of 16 kHz mono PCM16 at the pace of live audio and prints each event.

import asyncio
import json
import os

import websockets

URL = "wss://api.sprag.ai/v1/turns?model=sprag-eot"
HEADERS = {"Authorization": f"Bearer {os.environ['SPRAG_API_KEY']}"}
FRAME_BYTES = 3200  # 100 ms of 16 kHz PCM16


async def main() -> None:
    with open("caller.pcm", "rb") as clip:
        audio = clip.read()

    async with websockets.connect(URL, additional_headers=HEADERS) as ws:

        async def send() -> None:
            for start in range(0, len(audio), FRAME_BYTES):
                await ws.send(audio[start : start + FRAME_BYTES])
                await asyncio.sleep(0.1)
            await ws.send(json.dumps({"type": "session.close"}))

        sender = asyncio.create_task(send())
        async for message in ws:
            print(message)
        await sender


asyncio.run(main())
{"type":"session.created","session":{"id":"turns_23dd9a3875324eb58829e787","model":"sprag-eot","sample_rate":16000,"encoding":"pcm16","config":{"eot_threshold":0.6,"eager_eot_threshold":null,"min_silence_ms":200,"eot_timeout_ms":3000}}}
{"type":"turn.started","turn_index":0,"audio_window_start":0.096,"audio_window_end":0.096}
{"type":"turn.update","turn_index":0,"probability":0.08,"silence":0.224,"audio_window_start":0.096,"audio_window_end":3.296}
{"type":"turn.update","turn_index":0,"probability":0.61,"silence":0.512,"audio_window_start":0.096,"audio_window_end":10.784}
{"type":"turn.ended","turn_index":0,"reason":"model","probability":0.61,"silence":0.512,"audio_window_start":0.096,"audio_window_end":10.784}
{"type":"session.closed","usage":{"invocations":2}}

Connect

A session is one WebSocket connection that carries one caller's audio. Connect with the model id in the query string:

wss://api.sprag.ai/v1/turns?model=sprag-eot

The server sends session.created once the connection is accepted.

{
  "type": "session.created",
  "session": {
    "id": "turns_23dd9a3875324eb58829e787",
    "model": "sprag-eot",
    "sample_rate": 16000,
    "encoding": "pcm16",
    "config": {
      "eot_threshold": 0.6,
      "eager_eot_threshold": null,
      "min_silence_ms": 200,
      "eot_timeout_ms": 3000
    }
  }
}

Send the caller's audio as binary frames of 16-bit little-endian PCM, mono, at the rate in session.sample_rate. The session reads the binary frames as one stream of bytes, so a frame can be any length and can end partway through a sample. Every other frame, in either direction, is one JSON event.

For the two ways to pass your API key on a WebSocket upgrade, see Authentication.

How a session reads a turn

A turn opens when the caller starts speaking, and the server sends turn.started. A pause runs from the moment the caller stops speaking until the caller speaks again or the turn ends.

When a pause reaches min_silence_ms of silence, the model reads the audio up to that point, and the server sends the reading as turn.update. Further readings of the same pause follow while the pause lasts. If the caller speaks again before min_silence_ms, the pause has no reading.

A session is in one of three states, and each change of state has one cause.

The table lists what causes each change and the event the server sends.

FromCauseEventTo
No open turnThe caller starts speakingturn.startedSpeaking
SpeakingThe caller stops speakingNonePaused
PausedA reading below eot_thresholdturn.updatePaused
PausedThe caller speaks againturn.resumed after a turn.eager_end in the same pause, otherwise noneSpeaking
PausedA reading reaches eot_thresholdturn.update, then turn.ended with reason set to modelNo open turn
PausedThe silence reaches eot_timeout_msturn.ended with reason set to timeoutNo open turn
Speaking or pausedYou send turn.endturn.ended with reason set to clientNo open turn

turn.update arrives only during a pause. turn.resumed arrives only after a turn.eager_end in the same pause. turn_index rises by one with each turn.started.

A turn in which the caller pauses once and then finishes:

{"type":"turn.started","turn_index":0,"audio_window_start":7.012,"audio_window_end":7.012}
{"type":"turn.update","turn_index":0,"probability":0.08,"silence":0.224,"audio_window_start":7.012,"audio_window_end":9.12}
{"type":"turn.update","turn_index":0,"probability":0.52,"silence":0.224,"audio_window_start":7.012,"audio_window_end":10.496}
{"type":"turn.update","turn_index":0,"probability":0.61,"silence":0.512,"audio_window_start":7.012,"audio_window_end":10.784}
{"type":"turn.ended","turn_index":0,"reason":"model","probability":0.61,"silence":0.512,"audio_window_start":7.012,"audio_window_end":10.784}

Configure the session

To change a setting, send session.update with the fields to change under session. A field you leave out keeps its value.

{
  "type": "session.update",
  "session": { "eot_threshold": 0.7, "eager_eot_threshold": 0.4 }
}
FieldDefaultRangeEffect
eot_threshold0.60 to 1The probability that ends the turn.
eager_eot_thresholdnull0 to 1, at most eot_thresholdThe probability at which the server sends turn.eager_end. null turns the event off.
min_silence_ms2000 to 10,000 ms, below eot_timeout_msThe silence a pause needs before its first reading.
eot_timeout_ms3000100 to 60,000 msThe silence that ends the turn at any probability.

The server answers an accepted update with session.updated, whose session.config holds every setting now in force. If a value is out of range, the server sends an error event with the code invalid_event, and no field of the update applies.

Tune the settings

Change a setting when turns end at the wrong moment for your callers.

SettingRaise it toLower it to
eot_thresholdKeep more mid-sentence pauses inside the turn. Turns end later.End turns sooner. More turns end during a mid-sentence pause.
eager_eot_thresholdReceive fewer turn.eager_end events that a turn.resumed follows.Receive turn.eager_end earlier in a pause. More of them are followed by turn.resumed.
min_silence_msRead fewer pauses, which lowers the session's pause determinations. The earliest moment a turn can end moves later.Read shorter pauses, so a turn can end sooner after the caller stops.
eot_timeout_msGive a caller who pauses for a long time, such as one reading out a number, more time to continue.Shorten the longest silence before a reply.

To change a setting for part of a conversation, send session.update when that part starts and again when it ends. For example, raise eot_threshold while the caller reads out an account number, then restore it.

Receive an eager end

An eager end is an early sign that the turn is probably over. Set eager_eot_threshold below eot_threshold to receive it. The server sends turn.eager_end on the first reading in a pause whose probability reaches eager_eot_threshold, at most once per pause.

Use the three events to prepare a reply early:

  1. On turn.eager_end, start preparing the reply, for example by sending the turn to your language model. Do not play it yet.
  2. On turn.resumed, discard the reply you prepared. The turn stays open, and its next pause can send another turn.eager_end.
  3. On turn.ended, deliver the reply.

A turn in which the caller pauses, continues, and then finishes:

{"type":"turn.eager_end","turn_index":0,"probability":0.41,"silence":0.512,"audio_window_start":0.096,"audio_window_end":7.328}
{"type":"turn.resumed","turn_index":0,"audio_window_start":0.096,"audio_window_end":7.328}
{"type":"turn.eager_end","turn_index":0,"probability":0.56,"silence":0.224,"audio_window_start":0.096,"audio_window_end":10.496}
{"type":"turn.ended","turn_index":0,"reason":"model","probability":0.62,"silence":0.608,"audio_window_start":0.096,"audio_window_end":10.88}

If one reading reaches both thresholds, turn.eager_end arrives immediately before turn.ended. If the turn ends by eot_timeout_ms or by turn.end after a turn.eager_end, no turn.resumed arrives.

Every turn.eager_end that a turn.resumed follows is a reply you prepared and did not use. To prepare fewer unused replies, raise eager_eot_threshold. To end turns on turn.ended alone, leave eager_eot_threshold at null.

Send agent context

To give the model what the agent last said, send context.update with agent_text. Every later reading uses it. An empty string clears the context.

{ "type": "context.update", "agent_text": "What is your date of birth?" }

agent_text holds up to 20,000 characters.

End a turn

To end the open turn yourself, send turn.end. The server sends turn.ended with reason set to client.

{ "type": "turn.end" }
When you send turn.endResult
The caller is speakingturn.ended with probability set to null and silence set to 0.
The caller is in a pauseturn.ended with the pause's last reading as probability, or null when the pause has no reading.
A turn.eager_end has arrived in the current pauseturn.ended, with no turn.resumed.
No turn is openNo event. A second turn.end sent straight after the first has this result.

End turns on your own signal

To end turns on a signal of your own, such as a push-to-talk button or a keypad tone, set eot_threshold to 1 and send turn.end at each signal.

{
  "type": "session.update",
  "session": { "eot_threshold": 1, "eot_timeout_ms": 60000 }
}

With eot_threshold at 1, a reading ends the turn only when its probability is 1. turn.started and turn.update arrive as before, and each pause that has a reading is one pause determination.

If the silence reaches eot_timeout_ms before your turn.end, the server sends turn.ended with reason set to timeout.

Close the session

To close the session, send session.close. The server sends session.closed with the session's usage, then closes the socket with close code 1000.

{ "type": "session.closed", "usage": { "invocations": 9 } }

If you disconnect without sending session.close, no session.closed event arrives.

Events

EventMeaning
session.createdThe session exists. session carries its id, model, sample_rate, encoding, and config.
session.updatedA session.update was accepted. session.config holds the settings in force.
turn.startedThe caller started speaking and a turn opened.
turn.updateOne reading during a pause, with probability and silence.
turn.eager_endThe first reading in a pause to reach eager_eot_threshold, with probability and silence.
turn.resumedThe caller spoke again after a turn.eager_end.
turn.endedThe turn closed, with reason, probability, and silence.
session.closedThe session closed after session.close, with usage.
errorA rejected frame or a failed reading, with error.code and error.message.

Every turn event carries these fields:

FieldTypeNotes
turn_indexintegerThe turn's position in the session, counted from 0. Every event of one turn carries the same index.
audio_window_startnumberWhere the turn's speech began, in seconds from the session's first audio byte.
audio_window_endnumberThe position the event refers to, in seconds from the session's first audio byte.
probabilitynumber or nullThe probability that the caller has finished the turn. On turn.ended, the last reading of the turn's final pause, or null when that pause has no reading.
silencenumberSeconds of silence since the caller's last speech, up to audio_window_end.
reasonstringOn turn.ended: model, timeout, or client.

Usage

Turn detection is billed per pause determination. usage.invocations on session.closed counts the pause determinations the session is billed for. The first reading of each pause is one pause determination, and later readings of the same pause add none.

More information about the rate per pause determination can be found on the pricing page.

Errors

A session reports a rejected frame in band as an error event and stays open.

{ "type": "error", "error": { "code": "invalid_event", "message": "Value error, eager_eot_threshold must not exceed eot_threshold" } }
CodeCause
invalid_eventA JSON event with an unknown type, an unknown field, or a value out of range.
reading_failedA reading that returned no probability. The pause's next reading follows.

If your organization is at its cap of concurrent sessions, the WebSocket upgrade fails with HTTP 429 and the error code rate_limit_exceeded. More information about rate limits can be found in the API docs.

Close codeCause
1000Sent after session.closed.
1011Server error. Open a new session.
1013Sent when no replica can take the session; an error event with the code model_not_running or model_at_capacity arrives first. Retry with backoff.

See the errors reference for the full error shape and retry guidance.

Next steps

To score one finished clip in a single request, see API.

To run a session inside a Pipecat pipeline, see Pipecat: turn detection.