Detection sessions

Once the socket is open (see Connect), a session runs like this:

  1. Open the socket.
  2. Send one welcome frame as JSON text.
  3. Wait for the ready event.
  4. Stream audio as binary frames as the call plays. To send a recording faster than it plays, set amd.offline: true (see Answering machine detection). A frame can hold up to 256 KiB, so audio buffered before the socket opened can go in one frame; larger frames close the socket with 1009.
  5. Read detection and beep events as they arrive.
  6. Send {"command": "stop"} when the call ends. The server sends close, then stopped, then closes the socket with code 1000 (stop).

Open a new socket for the next call. Don't reconnect in the middle of a call: a new socket starts a new session with no memory of the audio so far.

To pool sockets instead, set "keep_alive": true on each welcome you want pooled. The socket then stays open after stopped and takes the next welcome. A pooled socket that gets no welcome within 60 seconds is closed with 1001 (idle). Sending {"type": "ping"} gets a pong back, but doesn't extend that window.

Welcome frame

{
  "type": "welcome",
  "payload": {
    "call_id": "4e8c2a6d-1f9b-4d3e-a5c7-2b6f8d4a9e31",
    "audio_encoding": "pcm16",
    "sample_rate_hz": 8000,
    "strategy": "standard"
  }
}
Field Type Required Description
call_id string No Your identifier. Echoed on every event and webhook.
audio_encoding string No pcm16 (16-bit little-endian, the default) or mulaw.
sample_rate_hz integer No 8000 (the default) or 16000.
strategy string No standard (the default), beep_only or live_check. See below.
detection_timeout_sec integer No Send timeout after this many seconds without a verdict. Default 45.
keep_alive boolean No Keep the socket open after stop so you can reuse it. Default false.
envelope string No flat sends every frame without a top-level type. See Flat frames.
amd object No Get one answer per call in Twilio's AnsweredBy values instead of detection events. See Answering machine detection.
webhook.url string No Also POST each event here. Not needed on this route, since events already arrive on the socket. A public HTTPS URL; private, loopback and link-local addresses are refused.
webhook.events array No Event names to deliver to webhook.url. Default: all of them.
webhook.headers object No Extra headers sent with each delivery, for example your own auth token.
Strategy Use it for
standard Live person versus voicemail, refined as more speech arrives, plus beep timing.
beep_only You already know it's voicemail and only need the beep.
live_check A faster live-person check, without the transcript-based refinement.

Events

Every event arrives as a JSON text frame:

{
  "type": "detection",
  "event": "detection",
  "payload": {
    "session_id": "6b2e9d4a-8f1c-4a7e-9d3b-5c8f2a6e1d47",
    "call_id": "4e8c2a6d-1f9b-4d3e-a5c7-2b6f8d4a9e31",
    "timestamp_ms": 2310,
    "type": "speech.voicemail.greeting",
    "confidence": 0.91,
    "beep_detected": false,
    "is_final": false,
    "is_refinement": false
  }
}

Every payload carries session_id, timestamp_ms and, if you sent one, call_id.

Event Meaning
ready The session is set up. Start streaming audio.
detection A verdict. type says who answered (see Verdict types). confidence is 0 to 1.
beep The voicemail beep ended. Start your message now. Carries timestamp_ms, frequency_hz, duration_ms, confidence and is_final, which is always true.
screening A call screener answered. Carries suggested_action and sometimes suggested_dtmf.
transcript, speech_start, speech_end, silence Progress while the call is classified. Safe to ignore.
timeout No verdict within detection_timeout_sec.
error Carries error, code and recoverable. If recoverable is false, the session is over.
close The session ended. Carries reason and duration_ms.
stopped Your stop command was processed.

Flat frames

Some clients act on a frame's top-level type, or drop frames whose type they don't know. For those, set "envelope": "flat" in the welcome. Every frame the server sends on that session then has only event and payload:

{
  "event": "ready",
  "payload": {
    "session_id": "6b2e9d4a-8f1c-4a7e-9d3b-5c8f2a6e1d47",
    "call_id": "4e8c2a6d-1f9b-4d3e-a5c7-2b6f8d4a9e31",
    "timestamp_ms": 0,
    "message": "Detection session ready"
  }
}

That holds for every event, including pong, error and the close sent before the socket closes. Payloads are unchanged, so a detection payload still carries its own type. On a keep_alive socket, a pong between calls follows the envelope of the last welcome. An envelope other than flat gets an error with code: "invalid_envelope", and the socket closes with 1008 (envelope rejected).

If the server is full when your welcome arrives, you get an error with code: "session_cap" and recoverable: true, and the socket stays open. Send the welcome again after a short wait, or carry on with the call without detection.

Verdict types

The type on a detection event is one of:

type Meaning Typical action
speech.human.unknown A live person answered. Connect your agent or play your live message.
speech.voicemail.greeting A voicemail greeting is playing. Keep streaming, wait for beep, then play your message.
speech.voicemail.full The mailbox is full. Hang up. It can't take a message.
speech.voicemail.not_setup The mailbox isn't set up. Hang up.
speech.silence The call was answered but nobody spoke. Hang up, or retry later.
speech.ivr A phone menu answered. Your choice.
speech.screening A call screener answered. A screening event carries the details. Follow the screening event.
speech.carrier.intercept A carrier message, such as "the number you have dialed is not in service". Hang up and mark the number.
speech.unknown Not classified. Treat as no result.

Match a live person on the speech.human. prefix, so a later subtype still counts. Treat any value you don't recognize as no result.

Some payloads also carry scores. Its keys are internal model labels that can change, so don't route on them.

Acting on verdicts

A detection event can be followed by a better one:

  • is_refinement: true means this verdict replaces an earlier one, because more speech arrived.
  • is_final: true means no further verdict follows.

An early live-person verdict can arrive with confidence 0.6 after a short greeting and a pause, and a refinement may follow. A threshold above 0.6 will miss many people who just say "hello".

A common pattern:

  • On the first type starting with speech.human., at confidence 0.6 or more, connect the agent.
  • On speech.voicemail.greeting, keep streaming, wait for beep, then play your message.
  • On speech.voicemail.full or speech.voicemail.not_setup, hang up.
  • On speech.silence or timeout, hang up or retry later.
function onDetection(payload) {
  const type = payload.type || '';
  if (type.startsWith('speech.human.') && payload.confidence >= 0.6) return 'connect_agent';
  if (type === 'speech.voicemail.greeting') return 'wait_for_beep';
  if (type === 'speech.voicemail.full' || type === 'speech.voicemail.not_setup') return 'hang_up';
  if (type === 'speech.silence') return 'hang_up';
  if (type === 'speech.carrier.intercept') return 'hang_up_and_mark_number';
  return 'no_result';
}

Answering machine detection

If your dialer already acts on Twilio's AnsweredBy, add an amd object to the welcome. The session then sends one amd_result per call, in the same values:

{
  "type": "welcome",
  "payload": {
    "call_id": "4e8c2a6d-1f9b-4d3e-a5c7-2b6f8d4a9e31",
    "audio_encoding": "pcm16",
    "sample_rate_hz": 8000,
    "amd": { "mode": "DetectMessageEnd" }
  }
}
Field Type Required Description
amd.mode string Yes Enable answers as soon as it knows who picked up. DetectMessageEnd answers a machine only once its greeting ends, so you can start your message.
amd.human_verdict string No first (the default) answers human on the first sign of a person. final waits until that is confirmed, which answers later for real people.
amd.timeout_sec integer No The longest to wait. When it runs out you get the best answer so far, or unknown. 3 to 59, default 30. Replaces detection_timeout_sec.
amd.silence_timeout_ms integer No Answer unknown when nobody speaks for this long from the start of your audio. 2000 to 10000, default 5000.
amd.offline boolean No true when you send a recording faster than it plays, for example to compare answers on past calls. timeout_sec and silence_timeout_ms then count audio received instead of time passed, so the answer matches the one a live call would get. Default false.

Values outside a range are moved to its nearest end. Any other mode or human_verdict, or an offline that isn't true or false, gets an error with code: "invalid_amd", and the socket closes with 1008 (amd rejected). human_verdict is matched without regard to case.

With offline, send binary frames of any size up to the 256 KiB limit. A second of 16 kHz PCM16 is 32 KiB. A session is billed for the audio it received or the time it was open, whichever is longer.

The answer arrives once, before close, even when you stop the call first:

{
  "type": "detection",
  "event": "amd_result",
  "payload": {
    "session_id": "6b2e9d4a-8f1c-4a7e-9d3b-5c8f2a6e1d47",
    "call_id": "4e8c2a6d-1f9b-4d3e-a5c7-2b6f8d4a9e31",
    "timestamp_ms": 7480,
    "answered_by": "machine_end_beep",
    "duration_ms": 7480,
    "detail": { "cause": "beep", "beep_end_ms": 7400 }
  }
}

duration_ms is the time from the start of your audio to the answer.

answered_by Meaning
human A live person answered.
machine_start A machine answered. Enable only.
machine_end_beep The greeting ended with a beep. Start your message now. DetectMessageEnd only.
machine_end_silence The greeting ended and no beep followed. Start your message now. DetectMessageEnd only.
machine_end_other A machine that won't take a message, such as a full mailbox, or a greeting still playing at timeout_sec. DetectMessageEnd only.
fax A fax machine or modem answered.
unknown No answer: nobody spoke, or nothing was recognized in time.

detail.cause says what the answer rests on:

cause Meaning
human A person spoke.
greeting A voicemail greeting.
greeting_end The greeting ended and no beep followed.
beep The voicemail beep. beep_end_ms is when it ended, from the start of your audio.
full_mailbox The mailbox is full.
not_setup The mailbox isn't set up.
intercept A carrier message, such as "the number you have dialed is not in service".
ivr A phone menu.
screener A call screener. A screening event carries the details.
silence The call connected but nobody spoke within silence_timeout_ms.
fax A fax or modem tone.
timeout Nothing recognized by timeout_sec.
unknown The call ended before anything was recognized.

Route on answered_by. Treat a cause you don't recognize as no cause.

With amd set, amd_result takes the place of detection. The session doesn't send detection, transcript, speech_start, speech_end or silence, and no event carries confidence. beep still arrives, with timestamp_ms and is_final only. screening still carries suggested_action and sometimes suggested_dtmf. Webhook deliveries carry the same events and fields as the socket.

Close codes

Code Reason What to do
1000 stop Normal end after stopped.
1001 idle No welcome within 60 seconds. Open a new socket for the next call.
1003 bad welcome json, or none The first frame wasn't a valid JSON welcome sent as text. Send the welcome as a text frame before any audio.
1008 webhook rejected webhook.url isn't a public HTTPS URL. Fix it and reconnect.
1008 amd rejected amd.mode, amd.human_verdict or amd.offline isn't one of the listed values. The error event before the close says which. Fix the welcome and reconnect.
1008 daily minute cap On a keep_alive socket, the key reached its daily_minute_cap between calls. An error event with code: "daily_minute_cap" comes first. Reconnect on the next UTC day, or raise the cap.
1008 envelope rejected envelope isn't flat. An error event with code: "invalid_envelope" comes first. Fix the welcome and reconnect.
1009 A frame was larger than 256 KiB. Send audio in smaller frames.

Code samples

The requests from this page, ready to copy. Set DC_KEY and DC_SECRET to your API key pair first.

Acting on verdicts
function onDetection(payload) {
  const type = payload.type || '';
  if (type.startsWith('speech.human.') && payload.confidence >= 0.6) return 'connect_agent';
  if (type === 'speech.voicemail.greeting') return 'wait_for_beep';
  if (type === 'speech.voicemail.full' || type === 'speech.voicemail.not_setup') return 'hang_up';
  if (type === 'speech.silence') return 'hang_up';
  if (type === 'speech.carrier.intercept') return 'hang_up_and_mark_number';
  return 'no_result';
}