Skip to Content
Assistant Core

Voice API

Create a voice session from your backend, then stream audio and receive speech over a WebSocket.

A voice integration has two steps: your backend creates a session with the API key, and the client opens a WebSocket with the session's short-lived token. The API key never leaves your backend.

This is an advanced Preview path. There is no browser voice SDK, WebRTC transport, or microphone and playback helper. Use it only if your client can capture, resample, encode, play, and cancel audio itself.

Before you begin

  • The API key has the voice:connect scope.
  • Voice is turned on for the assistant and its voice models are set (see Enable voice). Otherwise session creation returns 403 VOICE_DISABLED or 503 UPSTREAM_UNAVAILABLE.
  • You know which mode you need: standard (speech recognition, chat model, then speech synthesis) or realtime (a speech-to-speech model). See Standard vs realtime.

Allow your website's origin (browsers only)

A browser sends an Origin header, and the WebSocket accepts it only if the origin is on the assistant's list:

  1. In the Admin Panel, open Developer API.
  2. Under Voice browser access, enter the exact origin in Website origin, for example https://voice.example.com, and select Add origin. The origin saves right away.

Scheme, host, and port must match exactly. This list is separate from the Web Widget's allowed websites. Server, mobile, and desktop clients that send no Origin skip this step. A browser from an unlisted origin is disconnected with close code 1008.

Create a session from your backend

POST /v1/voice/sessions ยท scope voice:connect

curl "$ASSISTANT_API_URL/v1/voice/sessions" \
  --request POST \
  --header "Authorization: Bearer $ASSISTANT_API_KEY" \
  --header "Content-Type: application/json" \
  --data "{
    \"external_user_id\": \"$EXTERNAL_USER_ID\",
    \"mode\": \"standard\",
    \"turn_detection\": \"server_vad\",
    \"input_audio_format\": { \"codec\": \"pcm_s16le\", \"sample_rate_hz\": 16000, \"channels\": 1 },
    \"output_audio_format\": { \"codec\": \"opus\", \"sample_rate_hz\": 24000, \"channels\": 1 }
  }"
FieldRequiredMeaning
external_user_idYes1โ€“256 characters; your stable ID for the end user.
modeYesstandard or realtime.
input_audio_formatYescodec: pcm_s16le (16000 or 24000 Hz) or opus (24000 Hz only); channels: 1.
output_audio_formatYesSame options as input.
turn_detectionNomanual (you end each turn) or server_vad (the server hears where turns end), in either mode. Defaults to manual in standard and server_vad in realtime.
conversation_idNoContinue a conversation owned by the same end user.
max_session_secondsNo10โ€“1800. Defaults to 1800.
include_metricsNotrue sends response.metrics after each completed response. Default false.
emotionNoStandard only. true sends response.emotion before each reply's audio. Default false; realtime returns 422.
languageNoStandard only: vi or en. Speech recognition and synthesis language for this session instead of the assistant's spoken language.

201 response:

{
  "id": "sess_9b2f4e1c7a6d4b0e8f3a2c1d5e6f7a8b",
  "model": "gemini-3.8-flash",
  "token": "<session-token>",
  "expires_at": "2026-10-20T08:32:00Z",
  "websocket_url": "wss://api.assistantcore.com/v1/voice"
}

model is the chat model (standard) or the realtime model the session uses. Return only token, expires_at, and websocket_url to your signed-in client. The token works once and expires after 120 seconds.

ErrorCause
402 INSUFFICIENT_CREDITSThe owner is out of credits.
403 VOICE_DISABLEDVoice is off for the assistant.
404 CONVERSATION_NOT_FOUNDconversation_id is not this end user's.
422 VALIDATION_ERRORInvalid field combination, for example Opus at 16000 Hz, or manual with a realtime model that needs continuous input.
503 UPSTREAM_UNAVAILABLENo voice model is configured for the chosen mode.

Realtime sessions are billed after the session, so max_session_seconds is also capped at what the owner's credits cover. A session that reaches that cap ends with INSUFFICIENT_CREDITS instead of SESSION_DURATION_EXCEEDED. In standard mode, each turn is checked against the owner's credits; a turn they do not cover fails with INSUFFICIENT_CREDITS and the session stays open.

Native apps follow the same pattern: the app signs in to your backend, your backend creates the session, and the app receives only the token. Never ship an API key inside an app binary.

Open the WebSocket

Connect to the returned websocket_url. Within 15 seconds, send session.start as the first message. Do not put the token in the URL. Otherwise the server sends error with INVALID_EVENT_ORDER (INVALID_EVENT for invalid JSON, EVENT_TOO_LARGE for an oversized event) and closes with 1008.

{ "type": "session.start", "token": "<session-token>" }

When the session is ready, the server sends:

{ "type": "session.created", "sequence": 1, "session_id": "sess_9b2f4e1c7a6d4b0e8f3a2c1d5e6f7a8b" }

session.start may also carry a conversation_id to continue. Every server JSON event has a sequence that starts at 1 and increases by 1. Binary server messages are audio in the output format you chose.

const session = await fetch("/api/assistant/voice-session", { method: "POST" }).then((r) => r.json())

const socket = new WebSocket(session.websocket_url)
socket.binaryType = "arraybuffer"

socket.addEventListener("open", () => {
  socket.send(JSON.stringify({ type: "session.start", token: session.token }))
})

socket.addEventListener("message", (message) => {
  if (typeof message.data !== "string") {
    // Queue message.data for playback in the negotiated output format.
    return
  }
  const event = JSON.parse(message.data)
  if (event.type === "error") console.error(event.error.code, event.error.message)
})

socket.addEventListener("close", () => {
  // The token is spent. Ask your backend for a new session before reconnecting.
})

In standard mode, if the assistant has a voice greeting and the session starts a new conversation, the greeting plays right after session.created as a normal response (response.created, output_audio.*, then response.completed without message_id). Speech or response.cancel interrupts it.

Send text or audio

Send text instead of audio:

{ "type": "input_text.create", "text": "What is your return policy?" }

In standard mode, file_ids attaches up to 10 images or documents uploaded for the same end user; text can then be empty:

{ "type": "input_text.create", "text": "Is this the right charger?", "file_ids": ["8d50c5c2-bf85-48a4-b252-8dc97410452c"] }

A file that is not this end user's returns FILE_NOT_FOUND, and no response starts.

To ask about an image by voice, add it first with input_file.add (standard only). It goes with the next turn, spoken or typed:

{ "type": "input_file.add", "file_ids": ["8d50c5c2-bf85-48a4-b252-8dc97410452c"] }
  • You can add files while a response plays; they wait for the next turn.
  • Files stay held through a turn that fails before it reaches the assistant, for example NO_SPEECH or INSUFFICIENT_CREDITS, and go with the next one.
  • At most 10 files are held. A typed turn's own file_ids count toward the same limit of 10.
  • A file that is not this end user's returns FILE_NOT_FOUND and is not held.
  • Held files live only in the session. After reconnecting, add them again.

Send audio as binary WebSocket messages after input_audio.start:

Turn detectionWhat to send
manual{"type":"input_audio.start"}, then audio frames, then {"type":"input_audio.commit"} for each turn.
server_vad{"type":"input_audio.start"} once after session.created, then stream audio continuously. Never send input_audio.commit; the server finds the end of each turn and answers once per turn.
  • pcm_s16le frames are raw signed 16-bit little-endian mono PCM with no WAV header. Opus frames are 24 kHz mono.
  • Send short, regular frames; each binary message can be at most 256 KiB.
  • In standard + server_vad, a short pause can end a turn early. If the user resumes speaking before that turn was transcribed, the server cancels it (response.completed with status: "cancelled", then input_audio.speech_started) and keeps its audio, so the next transcript.completed covers both parts.

Do not send new input while a response is active; you get RESPONSE_IN_PROGRESS. Cancel first. input_file.add is the exception.

Responses

Each committed turn, typed text, or greeting becomes one response:

  1. response.created with a new response_id.
  2. The response's events: text, tool calls, and audio. Every response.* and output_audio.* event carries the same response_id.
  3. Exactly one response.completed with that response_id and a status:
StatusMeaning
completedThe reply was spoken and saved (message_id).
cancelledresponse.cancel or the user's speech stopped it. If the reply was already saved, message_id and text are still set.
failedIt could not finish. An error event comes first, for example NO_SPEECH when the audio held no words, or INSUFFICIENT_CREDITS when the owner's credits do not cover the turn.
incompleteThe reply was spoken and saved (message_id) but is unfinished: it reached the output length or tool step limit (standard), or the provider cut it short (realtime).

Do not rely on where response.created falls among the input_audio.* and transcript.* events; realtime may open a response while the user is still speaking.

If a reply plays music, the track follows the speech inside the same response: a second output_audio.started with the track's title, its audio, then output_audio.stopped.

When the assistant ends the conversation, for example after the user says goodbye, the server closes the WebSocket with code 1000 right after response.completed. Let the buffered audio finish playing before you end the call.

Cancel and barge-in

{ "type": "response.cancel" }

Stop playback, discard buffered output audio, and wait for response.completed with status: "cancelled" before sending new input. With no active response, response.cancel does nothing and the server sends no event. With server_vad, the user speaking also cancels the active response: its response.completed comes before input_audio.speech_started, so audio you receive after it belongs to the next response. In standard, once the reply plays audio, speech must last about half a second to interrupt it: a cough or a short "uh-huh" leaves the reply playing and sends no event.

Client events

EventUse
session.startFirst message; carries token and optionally conversation_id.
input_audio.startOpens a manual turn, or the continuous stream for server_vad.
Binary messageAudio after input_audio.start.
input_audio.commitEnds a manual turn. Not allowed with server_vad.
input_text.createSends text instead of audio, with optional file_ids (standard).
input_file.addHolds file_ids for the next turn, spoken or typed (standard).
response.cancelCancels the active response, if any.
pingThe server replies pong.

Server events

EventFields and meaning
session.createdsession_id, conversation_id (if continuing). The session is ready.
conversation.createdconversation_id of a new conversation.
input_audio.speech_startedManual: input opened. Auto and server VAD: speech detected.
input_audio.speech_stoppedThe turn's audio is committed.
transcript.deltaRealtime: delta of the user's transcript.
transcript.completedtranscript: the user's final words.
response.createdresponse_id of a new response. See Responses.
response.emotionOnly with emotion: true: emotion and emoji, for example "happy" and "๐Ÿ™‚". At most once per reply, before its audio.
response.text.deltadelta of the assistant's text.
response.tool_call.startedcall_id, name: the assistant started a tool, such as a knowledge base search.
response.tool_call.completedcall_id, name, status (completed or failed).
output_audio.startedBinary audio follows. title is set when the audio is a music track.
output_audio.sentence_startStandard: text and display_text of the sentence about to play.
Binary messageAudio in the output format.
output_audio.stoppedThe reply's audio ended.
response.completedstatus (see Responses); message_id of the saved reply; text (standard).
response.metricsOnly with include_metrics: true; see below.
errorerror: { code, message, retryable }. See Errors and limits.
pongReply to ping.

Ignore event types you do not know; new ones can be added during Preview.

Latency metrics

With include_metrics: true, each completed response is followed by one response.metrics event. Cancelled and failed responses have none.

{
  "type": "response.metrics",
  "sequence": 42,
  "response_id": "resp_4f1a2b3c4d5e6f708192a3b4c5d6e7f8",
  "message_id": "7c1e2f4a-9b3d-4e5f-8a6b-1c2d3e4f5a6b",
  "end_of_utterance_ms": 610,
  "transcription_ms": 180,
  "llm_ttft_ms": 420,
  "tts_ttfb_ms": 150,
  "e2e_latency_ms": 1390
}
FieldFrom โ†’ to
end_of_utterance_msUser stops speaking โ†’ server commits the turn.
transcription_msTurn committed โ†’ final transcript.
llm_ttft_msFinal transcript โ†’ first model token.
tts_ttfb_msFirst speech request โ†’ first speech audio.
e2e_latency_msUser stops speaking โ†’ first reply audio sent.

Values are whole milliseconds measured on the server, so they exclude network time to your client. A field is left out when its stage was not measured. Realtime mode reports only e2e_latency_ms.

Reconnect

A token works once. After a lost connection:

  1. Discard the old token.
  2. Ask your backend for a new session, passing the previous conversation_id.
  3. Connect to the new websocket_url and send the new token.

Back off exponentially on retryable errors, and stop when the key, origin, plan, or credits are the problem.

Connection limits

LimitValue
JSON event size16 KiB
Binary frame size256 KiB
Events per connection50 per second
Inbound audio per connection10 MiB per minute
Input audio per session15 minutes
Session length30 minutes, or less with max_session_seconds or a credit cap
Idle time2 minutes without a client event other than ping, detected speech, or a response in progress. With server_vad, streamed silence does not count.
Open connections5 per API key, 50 per assistant

Session creation also counts against the assistant's rate limits (see Errors and limits).

Last updated on