# Voice API

URL: https://docs.assistantcore.com/en/developers/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.

<Callout type="warn">
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.
</Callout>

## Before you begin [#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](/en/voice/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](/en/voice/standard-vs-realtime).

## Allow your website's origin (browsers only) [#allow-your-websites-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](https://admin.assistantcore.com), 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 [#create-a-session-from-your-backend]

`POST /v1/voice/sessions` · scope `voice:connect`

```bash
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:

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

<Callout type="info">
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.
</Callout>

## Open the WebSocket [#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`.

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

When the session is ready, the server sends:

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

```js
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-or-audio]

Send text instead of audio:

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

In `standard` mode, `file_ids` attaches up to 10 images or documents [uploaded](/en/developers/chat-api#upload-a-file) for the same end user; `text` can then be empty:

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

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

| 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 [#cancel-and-barge-in]

```json
{ "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 [#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 [#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](#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](#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](/en/developers/errors-limits). |
| `pong` | Reply to `ping`. |

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

## Latency metrics [#latency-metrics]

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

```json
{
  "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 [#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 [#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](/en/developers/errors-limits)).

<Cards>
<Card title="Errors and limits" description="Voice error codes and WebSocket close codes." href="/en/developers/errors-limits" />

<Card title="Standard vs realtime" description="Choose the voice mode for your use case." href="/en/voice/standard-vs-realtime" />
</Cards>