<!-- generated: do not edit. source: content/docs/turns/websocket.md -->

# Turn detection over a WebSocket

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.

```python
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())
```

```json
{"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:

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

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

```json
{
  "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](/docs/stt/api#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.

```mermaid
stateDiagram-v2
    accTitle: The states of a turn detection session
    direction LR
    idle: No open turn
    speaking: Speaking
    paused: Paused
    idle --> speaking: turn.started
    speaking --> paused: caller stops speaking
    paused --> paused: turn.update
    paused --> speaking: caller speaks again
    paused --> idle: turn.ended
    speaking --> idle: turn.ended (client)
```

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

| From | Cause | Event | To |
| --- | --- | --- | --- |
| No open turn | The caller starts speaking | `turn.started` | Speaking |
| Speaking | The caller stops speaking | None | Paused |
| Paused | A reading below `eot_threshold` | `turn.update` | Paused |
| Paused | The caller speaks again | `turn.resumed` after a `turn.eager_end` in the same pause, otherwise none | Speaking |
| Paused | A reading reaches `eot_threshold` | `turn.update`, then `turn.ended` with `reason` set to `model` | No open turn |
| Paused | The silence reaches `eot_timeout_ms` | `turn.ended` with `reason` set to `timeout` | No open turn |
| Speaking or paused | You send `turn.end` | `turn.ended` with `reason` set to `client` | No 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:

```json
{"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.

```json
{
  "type": "session.update",
  "session": { "eot_threshold": 0.7, "eager_eot_threshold": 0.4 }
}
```

| Field | Default | Range | Effect |
| --- | --- | --- | --- |
| `eot_threshold` | `0.6` | 0 to 1 | The probability that ends the turn. |
| `eager_eot_threshold` | `null` | 0 to 1, at most `eot_threshold` | The probability at which the server sends `turn.eager_end`. `null` turns the event off. |
| `min_silence_ms` | `200` | 0 to 10,000 ms, below `eot_timeout_ms` | The silence a pause needs before its first reading. |
| `eot_timeout_ms` | `3000` | 100 to 60,000 ms | The 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.

| Setting | Raise it to | Lower it to |
| --- | --- | --- |
| `eot_threshold` | Keep more mid-sentence pauses inside the turn. Turns end later. | End turns sooner. More turns end during a mid-sentence pause. |
| `eager_eot_threshold` | Receive 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_ms` | Read 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_ms` | Give 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:

```json
{"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.

```json
{ "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`.

```json
{ "type": "turn.end" }
```

| When you send `turn.end` | Result |
| --- | --- |
| The caller is speaking | `turn.ended` with `probability` set to `null` and `silence` set to `0`. |
| The caller is in a pause | `turn.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 pause | `turn.ended`, with no `turn.resumed`. |
| No turn is open | No 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.

```json
{
  "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`.

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

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

## Events

| Event | Meaning |
| --- | --- |
| `session.created` | The session exists. `session` carries its `id`, `model`, `sample_rate`, `encoding`, and `config`. |
| `session.updated` | A `session.update` was accepted. `session.config` holds the settings in force. |
| `turn.started` | The caller started speaking and a turn opened. |
| `turn.update` | One reading during a pause, with `probability` and `silence`. |
| `turn.eager_end` | The first reading in a pause to reach `eager_eot_threshold`, with `probability` and `silence`. |
| `turn.resumed` | The caller spoke again after a `turn.eager_end`. |
| `turn.ended` | The turn closed, with `reason`, `probability`, and `silence`. |
| `session.closed` | The session closed after `session.close`, with `usage`. |
| `error` | A rejected frame or a failed reading, with `error.code` and `error.message`. |

Every turn event carries these fields:

| Field | Type | Notes |
| --- | --- | --- |
| `turn_index` | integer | The turn's position in the session, counted from 0. Every event of one turn carries the same index. |
| `audio_window_start` | number | Where the turn's speech began, in seconds from the session's first audio byte. |
| `audio_window_end` | number | The position the event refers to, in seconds from the session's first audio byte. |
| `probability` | number or null | The 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. |
| `silence` | number | Seconds of silence since the caller's last speech, up to `audio_window_end`. |
| `reason` | string | On `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](/pricing) page.

## Errors

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

```json
{ "type": "error", "error": { "code": "invalid_event", "message": "Value error, eager_eot_threshold must not exceed eot_threshold" } }
```

| Code | Cause |
| --- | --- |
| `invalid_event` | A JSON event with an unknown `type`, an unknown field, or a value out of range. |
| `reading_failed` | A 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](/docs/api/rate-limits) can be found in the API
docs.

| Close code | Cause |
| --- | --- |
| `1000` | Sent after `session.closed`. |
| `1011` | Server error. Open a new session. |
| `1013` | Sent 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](/docs/api/errors) for the full error shape and retry
guidance.

## Next steps

To score one finished clip in a single request, see [API](/docs/turns/api).

To run a session inside a Pipecat pipeline, see
[Pipecat: turn detection](/docs/integrations/pipecat/turns).
