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:connectscope. - Voice is turned on for the assistant and its voice models are set (see Enable voice). Otherwise session creation returns
403 VOICE_DISABLEDor503 UPSTREAM_UNAVAILABLE. - You know which mode you need:
standard(speech recognition, chat model, then speech synthesis) orrealtime(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:
- In the Admin Panel, open Developer API.
- 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 }
}"| Field | Required | Meaning |
|---|---|---|
external_user_id | Yes | 1โ256 characters; your stable ID for the end user. |
mode | Yes | standard or realtime. |
input_audio_format | Yes | codec: pcm_s16le (16000 or 24000 Hz) or opus (24000 Hz only); channels: 1. |
output_audio_format | Yes | Same options as input. |
turn_detection | No | manual (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_id | No | Continue a conversation owned by the same end user. |
max_session_seconds | No | 10โ1800. Defaults to 1800. |
include_metrics | No | true sends response.metrics after each completed response. Default false. |
emotion | No | Standard only. true sends response.emotion before each reply's audio. Default false; realtime returns 422. |
language | No | Standard 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.
| Error | Cause |
|---|---|
402 INSUFFICIENT_CREDITS | The owner is out of credits. |
403 VOICE_DISABLED | Voice is off for the assistant. |
404 CONVERSATION_NOT_FOUND | conversation_id is not this end user's. |
422 VALIDATION_ERROR | Invalid field combination, for example Opus at 16000 Hz, or manual with a realtime model that needs continuous input. |
503 UPSTREAM_UNAVAILABLE | No 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_SPEECHorINSUFFICIENT_CREDITS, and go with the next one. - At most 10 files are held. A typed turn's own
file_idscount toward the same limit of 10. - A file that is not this end user's returns
FILE_NOT_FOUNDand 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 detection | What 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_s16leframes 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.completedwithstatus: "cancelled", theninput_audio.speech_started) and keeps its audio, so the nexttranscript.completedcovers 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:
response.createdwith a newresponse_id.- The response's events: text, tool calls, and audio. Every
response.*andoutput_audio.*event carries the sameresponse_id. - Exactly one
response.completedwith thatresponse_idand astatus:
| Status | Meaning |
|---|---|
completed | The reply was spoken and saved (message_id). |
cancelled | response.cancel or the user's speech stopped it. If the reply was already saved, message_id and text are still set. |
failed | It 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. |
incomplete | The 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
| Event | Use |
|---|---|
session.start | First message; carries token and optionally conversation_id. |
input_audio.start | Opens a manual turn, or the continuous stream for server_vad. |
| Binary message | Audio after input_audio.start. |
input_audio.commit | Ends a manual turn. Not allowed with server_vad. |
input_text.create | Sends text instead of audio, with optional file_ids (standard). |
input_file.add | Holds file_ids for the next turn, spoken or typed (standard). |
response.cancel | Cancels the active response, if any. |
ping | The server replies pong. |
Server events
| Event | Fields and meaning |
|---|---|
session.created | session_id, conversation_id (if continuing). The session is ready. |
conversation.created | conversation_id of a new conversation. |
input_audio.speech_started | Manual: input opened. Auto and server VAD: speech detected. |
input_audio.speech_stopped | The turn's audio is committed. |
transcript.delta | Realtime: delta of the user's transcript. |
transcript.completed | transcript: the user's final words. |
response.created | response_id of a new response. See Responses. |
response.emotion | Only with emotion: true: emotion and emoji, for example "happy" and "๐". At most once per reply, before its audio. |
response.text.delta | delta of the assistant's text. |
response.tool_call.started | call_id, name: the assistant started a tool, such as a knowledge base search. |
response.tool_call.completed | call_id, name, status (completed or failed). |
output_audio.started | Binary audio follows. title is set when the audio is a music track. |
output_audio.sentence_start | Standard: text and display_text of the sentence about to play. |
| Binary message | Audio in the output format. |
output_audio.stopped | The reply's audio ended. |
response.completed | status (see Responses); message_id of the saved reply; text (standard). |
response.metrics | Only with include_metrics: true; see below. |
error | error: { code, message, retryable }. See Errors and limits. |
pong | Reply 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
}| Field | From โ to |
|---|---|
end_of_utterance_ms | User stops speaking โ server commits the turn. |
transcription_ms | Turn committed โ final transcript. |
llm_ttft_ms | Final transcript โ first model token. |
tts_ttfb_ms | First speech request โ first speech audio. |
e2e_latency_ms | User 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:
- Discard the old token.
- Ask your backend for a new session, passing the previous
conversation_id. - Connect to the new
websocket_urland send the new token.
Back off exponentially on retryable errors, and stop when the key, origin, plan, or credits are the problem.
Connection limits
| Limit | Value |
|---|---|
| JSON event size | 16 KiB |
| Binary frame size | 256 KiB |
| Events per connection | 50 per second |
| Inbound audio per connection | 10 MiB per minute |
| Input audio per session | 15 minutes |
| Session length | 30 minutes, or less with max_session_seconds or a credit cap |
| Idle time | 2 minutes without a client event other than ping, detected speech, or a response in progress. With server_vad, streamed silence does not count. |
| Open connections | 5 per API key, 50 per assistant |
Session creation also counts against the assistant's rate limits (see Errors and limits).
Last updated on