# Health Source: https://docs.sayna.ai/api-reference/endpoint/health GET / Simple readiness probe that reports the Sayna process status. Combine it with Kubernetes liveness checks or deployment smoke tests. # Remove LiveKit participant Source: https://docs.sayna.ai/api-reference/endpoint/livekit-participant DELETE /livekit/participant Removes a participant from a LiveKit room, forcibly disconnecting them. Access is authorized via `metadata.auth_id` check. Note: This does not invalidate the participant's token. To prevent rejoining, use short-lived tokens and avoid issuing new tokens to removed participants. # Arguments * `state` - Shared application state containing LiveKit configuration * `auth` - Authentication context from middleware * `request` - Request with room name and participant identity # Returns * `Response` - JSON response with removal status or error # Authorization - When `auth.id` is present: Requires `room.metadata.auth_id == auth.id` - When `auth.id` is absent: Access is allowed (backward-compatible mode) # Errors * 400 Bad Request - Empty room name or participant identity * 404 Not Found - Room/participant not found or access denied (masked) * 500 Internal Server Error - LiveKit not configured or removal failed # Flow 1. Validate request fields are not empty 2. Check room access via metadata.auth_id 3. Verify participant exists in the room 4. Remove the participant 5. Return success or appropriate error Removes a participant from a LiveKit room, forcibly disconnecting them. Access is authorized via `metadata.auth_id` check. ## Authorization | Mode | Behavior | | ---------------------------------- | --------------------------------------------- | | Authenticated (`auth.id` present) | Requires `room.metadata.auth_id == auth.id`. | | Unauthenticated (`auth.id` absent) | Access is allowed (backward-compatible mode). | Room names are used exactly as provided. No prefixing or modification is applied. ## Request Requires `room_name` and `participant_identity` in the request body. ## Error responses | Status | Condition | | --------------------------- | ------------------------------------------------------------------ | | `400 Bad Request` | Empty room name or participant identity. | | `404 Not Found` | Room/participant not found or access denied (masked for security). | | `500 Internal Server Error` | LiveKit not configured or removal failed. | This endpoint does not revoke the participant's token. To prevent rejoining, use short-lived tokens and avoid issuing new tokens to removed participants. # Mute LiveKit participant Source: https://docs.sayna.ai/api-reference/endpoint/livekit-participant-mute POST /livekit/participant/mute Mutes or unmutes a participant's published track. Access is authorized via `metadata.auth_id` check. # Arguments * `state` - Shared application state containing LiveKit configuration * `auth` - Authentication context from middleware * `request` - Request with room name, participant identity, track_sid, and muted state # Returns * `Response` - JSON response with mute status or error # Authorization - When `auth.id` is present: Requires `room.metadata.auth_id == auth.id` - When `auth.id` is absent: Access is allowed (backward-compatible mode) # Errors * 400 Bad Request - Empty fields in request * 404 Not Found - Room/participant not found or access denied (masked) * 500 Internal Server Error - LiveKit not configured or mute operation failed Mutes or unmutes a participant's published track. Access is authorized via `metadata.auth_id` check. ## Authorization | Mode | Behavior | | ---------------------------------- | --------------------------------------------- | | Authenticated (`auth.id` present) | Requires `room.metadata.auth_id == auth.id`. | | Unauthenticated (`auth.id` absent) | Access is allowed (backward-compatible mode). | Room names are used exactly as provided. No prefixing or modification is applied. ## Request Requires: * `room_name` - The LiveKit room where the participant is connected * `participant_identity` - The identity of the participant whose track to mute * `track_sid` - The session ID of the track to mute/unmute * `muted` - `true` to mute, `false` to unmute ## Error responses | Status | Condition | | --------------------------- | ------------------------------------------------------------------ | | `400 Bad Request` | Empty required fields in request. | | `404 Not Found` | Room/participant not found or access denied (masked for security). | | `500 Internal Server Error` | LiveKit not configured or mute operation failed. | # LiveKit room details Source: https://docs.sayna.ai/api-reference/endpoint/livekit-room GET /livekit/rooms/{room_name} Returns detailed information about a specific LiveKit room including all current participants. Access is authorized via `metadata.auth_id` check. # Arguments * `state` - Shared application state containing LiveKit configuration * `auth` - Authentication context from middleware * `room_name` - Name of the room to retrieve (from path parameter) # Returns * `Response` - JSON response with room details or error status # Authorization - When `auth.id` is present: Requires `room.metadata.auth_id == auth.id` - When `auth.id` is absent: Access is allowed (backward-compatible mode) # Errors * 404 Not Found - Room not found or access denied (masked as not found) * 500 Internal Server Error - LiveKit service not configured or API call failed Returns detailed information about a specific LiveKit room including all current participants. Access is authorized via `metadata.auth_id` check. ## Authorization | Mode | Behavior | | ---------------------------------- | --------------------------------------------- | | Authenticated (`auth.id` present) | Requires `room.metadata.auth_id == auth.id`. | | Unauthenticated (`auth.id` absent) | Access is allowed (backward-compatible mode). | Room names are used exactly as provided. No prefixing or modification is applied. ## Response Returns room details including: * `sid` - Unique session ID (generated by LiveKit) * `name` - The room name * `num_participants` - Current participant count * `max_participants` - Maximum allowed (0 = no limit) * `creation_time` - Unix timestamp * `metadata` - Room metadata (treat as opaque JSON) * `active_recording` - Whether recording is active * `participants` - List of participants with identities, metadata, and state ## Error responses | Status | Condition | | --------------------------- | ------------------------------------------------------ | | `404 Not Found` | Room not found or access denied (masked for security). | | `500 Internal Server Error` | LiveKit not configured or API call failed. | # LiveKit rooms Source: https://docs.sayna.ai/api-reference/endpoint/livekit-rooms GET /livekit/rooms Lists all LiveKit rooms belonging to the authenticated client. Rooms are filtered by `metadata.auth_id` for tenant isolation. # Arguments * `state` - Shared application state containing LiveKit configuration * `auth` - Authentication context from middleware # Returns * `Response` - JSON response with rooms list or error status # Filtering - When `auth.id` is present: Returns only rooms where `metadata.auth_id == auth.id` - When `auth.id` is absent: Returns all rooms (backward-compatible mode) # Errors * 500 Internal Server Error - LiveKit service not configured or API call failed Lists all LiveKit rooms belonging to the authenticated tenant. Rooms are filtered by `metadata.auth_id` for tenant isolation. ## Filtering behavior | Mode | Behavior | | ---------------------------------- | ------------------------------------------------------------------- | | Authenticated (`auth.id` present) | Returns only rooms where `metadata.auth_id` matches your tenant ID. | | Unauthenticated (`auth.id` absent) | Returns all rooms (backward-compatible mode). | This endpoint may return fewer rooms than exist in LiveKit when authentication is enabled. Each tenant only sees their own rooms. ## Response Returns `{ rooms: [...] }` with each room containing: * `name` - The room name (clean, no prefixes) * `num_participants` - Current participant count * `creation_time` - Unix timestamp when the room was created # LiveKit token Source: https://docs.sayna.ai/api-reference/endpoint/livekit-token POST /livekit/token Generates a LiveKit JWT token for a participant to join a specific room. When authentication is enabled (`auth.id` is present), this handler: 1. Creates the room if it doesn't exist 2. Sets `room.metadata.auth_id` to the authenticated tenant's ID 3. Issues the token only after metadata is verified/set # Arguments * `state` - Shared application state containing LiveKit configuration * `request` - Token request with room name and participant details # Returns * `Response` - JSON response with token or error status # Errors * 400 Bad Request - Invalid request data (empty fields) * 403 Forbidden - Room exists with a different tenant's `auth_id` * 500 Internal Server Error - LiveKit service not configured, room creation failed, or token generation failed Generates a LiveKit JWT token for a participant to join a specific room. When authentication is enabled, this endpoint also handles room creation and ownership. ## Room creation behavior When `auth.id` is present (authenticated mode): 1. If the room doesn't exist, Sayna creates it automatically. 2. The room's `metadata.auth_id` is set to your tenant ID. 3. The token is issued only after ownership is verified or established. Room names are used exactly as provided. No prefixing or modification is applied. ## Authorization | Scenario | Behavior | | ---------------------------- | -------------------------------------------------------------- | | Room doesn't exist | Room is created with `metadata.auth_id` set to your tenant ID. | | Room exists, you own it | Token is issued normally. | | Room exists, different owner | `403 Forbidden` is returned. | | Unauthenticated mode | Token is issued without ownership checks. | ## Error responses | Status | Condition | | --------------------------- | -------------------------------------------------- | | `400 Bad Request` | Missing or empty required fields. | | `403 Forbidden` | Room exists with a different tenant's `auth_id`. | | `500 Internal Server Error` | LiveKit not configured or token generation failed. | If you receive a `403`, the room already exists and is owned by another tenant. Choose a different room name rather than retrying with the same one. # Recording Source: https://docs.sayna.ai/api-reference/endpoint/recording GET /recording/{stream_id} Download the composite OGG recording for a completed session using the `stream_id` returned in the WebSocket `ready` message. Requires LiveKit recording to be enabled and storage configured; responds with `audio/ogg` and a download-friendly `Content-Disposition` header. When the session was configured with a [`loading_audio`](/guides/websocket#loading_audio-configuration) clip, the recording mixes both the `tts-audio` and `loading-audio` tracks exactly as the human participant heard them. # SIP call Source: https://docs.sayna.ai/api-reference/endpoint/sip-call POST /sip/call Initiates an outbound SIP call through LiveKit. The optional `sip` object in the request body allows overriding global SIP configuration on a per-request basis. Request body values take priority over global config, enabling different SIP providers or credentials for specific calls. Initiate an outbound SIP call through LiveKit. The call is connected to the specified room as a SIP participant, enabling real-time voice interactions with external phone numbers. Requires SIP configuration with an `outbound_address` and a valid SIP trunk. The room is created automatically if it doesn't exist, with `metadata.auth_id` set for tenant isolation. ## Request fields | Field | Type | Required | Description | | ---------------------- | ------ | -------- | --------------------------------------------------------------------------------------------------------- | | `room_name` | string | Yes | The LiveKit room to connect the call to. | | `participant_name` | string | Yes | Display name for the SIP participant in the room. | | `participant_identity` | string | Yes | Unique identity for the SIP participant. | | `from_phone_number` | string | Yes | Caller ID phone number (must be configured in your SIP provider). | | `to_phone_number` | string | Yes | Destination phone number to dial. | | `sip` | object | No | Per-request SIP configuration overrides. See [SIP configuration overrides](#sip-configuration-overrides). | ## SIP configuration overrides The optional `sip` object allows you to override global SIP configuration on a per-request basis. This is useful when you need to use different SIP providers or credentials for specific calls. | Field | Type | Description | | ------------------ | ------------ | ------------------------------------------------------------------- | | `outbound_address` | string\|null | SIP server address override. Format: `hostname` or `hostname:port`. | | `auth_username` | string\|null | SIP authentication username override. | | `auth_password` | string\|null | SIP authentication password override. | Existing requests without the `sip` object continue to work unchanged. The global server configuration is used when per-request overrides are not provided. ## Configuration priority When the `sip` object is provided, its fields take priority over global server configuration: **Request body `sip` config > Global server config** | Request Body Field | Overrides Global Config | | ---------------------- | ---------------------------- | | `sip.outbound_address` | `sip.outbound_address` | | `sip.auth_username` | `sip.outbound_auth_username` | | `sip.auth_password` | `sip.outbound_auth_password` | If neither the request body nor global config provides an `outbound_address`, the call will fail with an `OUTBOUND_ADDRESS_NOT_CONFIGURED` error. ## Example requests ```json Basic request theme={null} { "room_name": "call-room-123", "participant_name": "John Doe", "participant_identity": "caller-456", "from_phone_number": "+15105550123", "to_phone_number": "+15551234567" } ``` ```json With SIP configuration overrides theme={null} { "room_name": "call-room-123", "participant_name": "John Doe", "participant_identity": "caller-456", "from_phone_number": "+15105550123", "to_phone_number": "+15551234567", "sip": { "outbound_address": "sip.provider.com:5060", "auth_username": "user123", "auth_password": "secret456" } } ``` ## Authorization Access is controlled via room metadata: * When `auth.id` is present and the room exists: requires `room.metadata.auth_id == auth.id` * When `auth.id` is present and room doesn't exist: room is created with `metadata.auth_id` set * When `auth.id` is absent: access is allowed (backward-compatible mode) ## Error responses | Status | Condition | | --------------------------- | ---------------------------------------------------------------------- | | `400 Bad Request` | Invalid phone number format or empty required fields. | | `404 Not Found` | Room exists with a different tenant's `auth_id` (masked as not found). | | `500 Internal Server Error` | LiveKit not configured, outbound address missing, or call failed. | Phone numbers support international format (`+1234567890`), national format (`07123456789`), or internal extensions (`1234`). # SIP hooks Source: https://docs.sayna.ai/api-reference/endpoint/sip-hooks GET /sip/hooks Returns the current list of SIP hooks from runtime state. This endpoint requires authentication if `AUTH_REQUIRED=true`. # Returns * `200 OK` - List of SIP hooks * `500 Internal Server Error` - If reading the cache fails Lists all configured SIP hooks from the runtime state. Useful for debugging host-to-URL routing when forwarding LiveKit SIP webhooks. ## Response Returns `{ hooks: [...] }` with each hook containing: * `host` - Host pattern for matching SIP domains (case-insensitive) * `url` - HTTPS URL to forward webhook events to * `auth_id` - Tenant identifier for room ownership (used for `metadata.auth_id`) The `auth_id` field associates inbound SIP calls with a specific tenant. When a call arrives, Sayna sets the room's `metadata.auth_id` to this value for access control. ## Authorization Requires authentication when `AUTH_REQUIRED=true`. # Delete SIP hooks Source: https://docs.sayna.ai/api-reference/endpoint/sip-hooks-delete DELETE /sip/hooks Removes the specified hosts from the cache. Hosts defined in the application configuration cannot be removed. If a host exists in the original server configuration, it will revert to its config value after deletion of a cached override. Hosts that only exist in cache will be completely removed. The changes take effect immediately and persist across server restarts. # Request Body Array of host names to remove (case-insensitive). # Returns * `200 OK` - Updated list of SIP hooks after deletion * `400 Bad Request` - If the hosts array is empty * `500 Internal Server Error` - If writing the cache fails Remove SIP webhook forwarding entries by host name. * Body: `{ hosts: [] }` array of host names (case-insensitive); empty arrays are rejected. * Hosts present in server config revert to their config values after deletion; cache-only hosts are removed entirely. * Changes apply immediately and persist across restarts. Auth still applies when `AUTH_REQUIRED=true`; failures return 500 if cache writing fails. # Update SIP hooks Source: https://docs.sayna.ai/api-reference/endpoint/sip-hooks-update POST /sip/hooks Adds or replaces SIP hooks in the cache. Hooks with matching hosts (case-insensitive) will be replaced. Hosts defined in the application configuration cannot be modified. The changes take effect immediately and persist across server restarts. **Note**: Secrets are NOT stored in the cache. Runtime-added hooks will use the global `hook_secret` from the server configuration. # Request Body Array of hook entries with `host` and `url` fields. # Returns * `200 OK` - Updated list of SIP hooks * `400 Bad Request` - If validation fails (e.g., duplicate hosts) * `500 Internal Server Error` - If writing the cache fails Adds or replaces SIP webhook forwarding entries at runtime. Changes take effect immediately and persist across server restarts. ## Request body Array of hook entries with: * `host` - Host pattern for matching SIP domains (case-insensitive) * `url` - HTTPS URL to forward webhook events to * `auth_id` - Tenant identifier for room ownership The `auth_id` field is required when `AUTH_REQUIRED=true`. It determines which tenant owns rooms created from inbound SIP calls to this host. ## Behavior * Hooks with matching hosts (case-insensitive) are replaced; others are added. * Hosts defined in the application configuration cannot be modified via this endpoint. * Secrets are NOT stored in the cache. Runtime-added hooks use the global `hook_secret` from server configuration. ## Error responses | Status | Condition | | --------------------------- | ------------------------------------------------------------------------------------- | | `400 Bad Request` | Validation failed (duplicate hosts, non-HTTPS URLs, missing `auth_id` when required). | | `405 Method Not Allowed` | Attempted to modify a host defined in application config. | | `500 Internal Server Error` | Failed to write hooks cache. | # SIP transfer Source: https://docs.sayna.ai/api-reference/endpoint/sip-transfer POST /sip/transfer Initiates a SIP REFER transfer for a participant in a LiveKit room. The transfer moves an ongoing SIP call to a different phone number. # Arguments * `state` - Shared application state containing LiveKit handlers * `auth` - Authentication context for room metadata authorization * `request` - Transfer request with room name, participant identity, and destination # Returns * `Response` - JSON response with transfer status or error # Errors * 400 Bad Request - Invalid phone number format or empty fields * 404 Not Found - Room not found, not accessible, or participant not found * 500 Internal Server Error - LiveKit not configured or transfer operation failed # Flow 1. Validate the phone number format 2. Check LiveKit handlers are configured 3. Check room access via metadata auth_id 4. Verify the participant exists and is a SIP participant 5. Execute the SIP transfer 6. Return success or appropriate error Initiates a SIP REFER transfer for a participant in a LiveKit room. The transfer moves an ongoing SIP call to a different phone number. ## Authorization Access is controlled via room metadata: | Mode | Behavior | | ---------------------------------- | --------------------------------------------- | | Authenticated (`auth.id` present) | Requires `room.metadata.auth_id == auth.id`. | | Unauthenticated (`auth.id` absent) | Access is allowed (backward-compatible mode). | Room names are used exactly as provided. No prefixing or modification is applied. ## Request Requires: * `room_name` - The LiveKit room where the SIP participant is connected * `participant_identity` - The identity of the SIP participant to transfer * `transfer_to` - The destination phone number Phone numbers support international format (`+1234567890`), national format (`07123456789`), or internal extensions (`1234`). ## Response Returns `status` of `initiated` once the transfer request is accepted. A successful response indicates the transfer has been initiated, not that it has completed. ## Error responses | Status | Condition | | --------------------------- | ------------------------------------------------------------------------------ | | `400 Bad Request` | Invalid phone number format or empty required fields. | | `404 Not Found` | Room not found, access denied, or participant not found/not a SIP participant. | | `500 Internal Server Error` | LiveKit not configured or transfer operation failed. | Only SIP participants can be transferred. Use `GET /livekit/rooms/{room_name}` to check if a participant has `kind: "SIP"` before attempting a transfer. # Synthesize speech Source: https://docs.sayna.ai/api-reference/endpoint/speak POST /speak Kick off one-shot synthesis jobs for short responses. This endpoint reuses the same provider layer and cache that powers the streaming WebSocket experience. Reuse identical `tts_config` inputs to hit the cache and avoid extra provider round-trips. # List voices Source: https://docs.sayna.ai/api-reference/endpoint/voices GET /voices Discover every provider + voice combo configured on this Sayna deployment. The response mirrors upstream metadata (languages, sample rates, features) so you can drive in-product voice pickers. # API reference Source: https://docs.sayna.ai/api-reference/introduction Interactive REST docs powered by the Sayna OpenAPI specification. The Sayna API surface is intentionally focused: health checks, voice discovery, one-shot synthesis, LiveKit token + room management helpers, recording downloads, and SIP runtime controls. All request/response schemas live inside [`/api-reference/openapi.yaml`](/api-reference/openapi.yaml) and are rendered below via Mintlify's API Playground. Keep the OpenAPI file in sync with the server using `cargo run --features openapi -- openapi -o docs/openapi.yaml`. ## Authentication All REST endpoints honor the settings described in the [Authentication guide](/guides/authentication). When `AUTH_REQUIRED=true`, include a token via the `Authorization: Bearer ` header or the `api_key` query parameter. The header is recommended by default; use the query parameter in environments where custom headers are difficult to set. The playground lets you set the header once via the sidebar. ## Endpoints covered * `GET /` – health check * `GET /voices` – provider catalog * `POST /speak` – one-shot synthesis with caching * `POST /livekit/token` – mint LiveKit JWTs for participants * `GET /livekit/rooms` – list rooms scoped to the authenticated tenant * `GET /livekit/rooms/{room_name}` – fetch room details + participants * `DELETE /livekit/participant` – remove a participant from a room * `POST /livekit/participant/mute` – mute/unmute a participant track * `GET /recording/{stream_id}` – download a completed session recording * `POST /sip/call` – initiate an outbound SIP call * `GET /sip/hooks` – read the SIP webhook forwarding table * `POST /sip/hooks` – upsert SIP webhook forwarding entries * `DELETE /sip/hooks` – remove SIP webhook forwarding entries * `POST /sip/transfer` – transfer a SIP participant to a new destination See the [WebSocket guide](/guides/websocket) for streaming message schemas and LiveKit orchestration. # Platform architecture Source: https://docs.sayna.ai/guides/architecture How Sayna orchestrates WebSockets, providers, LiveKit, and SIP carriers into a single real-time voice service. Sayna sits between your apps, telecom carriers, and third-party speech providers. Use this page to understand the big-picture data flows before diving into specific APIs. Need request/response schemas? Pair this overview with the [REST API](/guides/rest-api), [WebSocket](/guides/websocket), and [SIP configuration](/guides/sip) references. ## System landscape ```mermaid theme={null} flowchart LR subgraph Clients A["Web & mobile apps
(WebSocket + REST)"] B["Backend jobs
(WebSocket or REST)"] end subgraph Carriers C["Twilio / SIP trunks
SIP INVITE over TCP"] end subgraph Sayna D["Edge & optional auth
TLS termination, bearer/JWT checks"] E["API & WebSocket gateway
/ws, /voices, /speak, /livekit/token"] F["Voice orchestrator
Sessions, caching, DSP"] G["Provider connectors
Deepgram STT/TTS, ElevenLabs TTS"] H["LiveKit transport
Room joiner, data channel, recording"] I["SIP hook router
Room prefix + webhook fan-out"] end subgraph Dependencies J["LiveKit cloud/self-host"] K["External auth service
(optional)"] L["Downstream webhooks
(per SIP domain)"] end A & B -->|/ws + binary audio| D --> E --> F --> G E --> H --> J C -->|SIP to Sayna domain| D F --> I --> L E -->|/livekit/token| J D -->|delegated JWT| K ``` ## Traffic entry points **WebSocket (`/ws`)** – The main control plane. Clients connect once, send a `config` payload (providers + LiveKit settings), and then stream audio, emit `speak` commands, or relay LiveKit data with sub-second latency. **REST endpoints** – Provide complementary one-off operations: * `/voices` lists provider catalogs for UI pickers. * `/speak` performs one-shot synthesis when a persistent socket is overkill. * `/livekit/token` mints participant tokens so browser/mobile clients can join the same LiveKit room that Sayna already inhabits. **SIP ingress** – When the `sip` block is populated, Sayna exposes a SIP domain/IP. Carriers such as Twilio point their Origination URI at that address (e.g., `sip:sip.sayna.ai;transport=tcp`). Sayna enforces `room_prefix` constraints, filters source IPs, and forwards LiveKit webhook payloads to the hosts defined in `SIP_HOOKS_JSON`. ## Voice orchestration pipeline 1. **Configuration** – Sayna validates the `config` message, injects server-side API keys (or uses client-supplied credentials when provided via the `auth` field), initializes STT/TTS providers, loads DSP assets (turn detection, noise filtering), and emits `ready` once everything is live. 2. **Streaming** – Binary frames flow through the STT connector; `stt_result` events stream back with `is_final` and `is_speech_final` hints so you know when to respond. 3. **Synthesis** – `speak` commands enqueue TTS jobs. Audio streams back as binary frames and, when LiveKit is enabled, mirrors into the room for human listeners. 4. **Caching** – TTS outputs are hashed by text + config and stored under `CACHE_PATH`, so repeated prompts replay instantly. 5. **Error handling** – Most faults surface as JSON `error` events while keeping the socket open, giving clients room to retry. ## LiveKit & SIP interplay * Sayna runs its own LiveKit participant (identity defaults to `sayna-ai`). Other clients call `/livekit/token` to get their own access tokens; Sayna never shares its agent keys. * When `enable_recording=true`, Sayna asks LiveKit to start composite recordings to the S3 target you configured. * SIP mode auto-provisions the LiveKit SIP trunk + dispatch rule (`sayna-{room_prefix}-trunk/dispatch`). You only configure the carrier; Sayna takes care of LiveKit. * The SIP dispatcher reads `sip.h.to` headers from LiveKit webhook events and forwards the raw JSON payload to whichever hook hostname matches—perfect for per-domain routing or downstream analytics. ## Component responsibilities | Component | Purpose | Key considerations | | ----------------------- | --------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | | Edge & optional auth | Terminates TLS/WebSockets and enforces API secret or delegated JWT policies before traffic reaches `/ws` or REST handlers. | Pair with `AUTH_REQUIRED=true` when exposing Sayna on the public internet. | | API & WebSocket gateway | Hosts `/ws`, `/voices`, `/speak`, `/livekit/token`, validates payloads, and multiplexes JSON/binary frames. | Idle sockets close after \~10 s; errors rarely tear down the connection. | | Voice orchestrator | Manages per-session state (providers, caches, DSP), schedules STT/TTS work, and prevents mismatched streams. | Configuration drives everything—use consistent `stt_config` and `tts_config` when you need cache hits. | | Provider connectors | Abstract Deepgram STT/TTS and ElevenLabs TTS behind a unified schema. | Outbound HTTPS is required; provide the relevant API keys via env vars or per-session via the `auth` config field. | | LiveKit transport | Joins rooms, mirrors Sayna’s audio into WebRTC, relays data-channel messages, and coordinates recordings. | `/livekit/token` keeps your own agentic logic and participants in sync with Sayna’s LiveKit room. | | SIP hook router | Enforces `room_prefix`, respects `SIP_ALLOWED_ADDRESSES`, and forwards webhook payloads to domain-specific HTTPS endpoints. | Combine with [Twilio SIP setup](/guides/sip-twilio) when routing PSTN callers into Sayna. | ## Common deployment patterns | Pattern | Flow | | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **WebSocket-only assistant** | App connects to `/ws` → sends `config` (no LiveKit) → streams mic audio → reacts to `stt_result` → sends `speak` for replies. | | **Hybrid WebSocket + LiveKit** | Sayna joins LiveKit via config → browsers fetch `/livekit/token` and join the room → LiveKit audio feeds Sayna’s STT, `speak` audio mirrors back to participants, data-channel messages sync UI state. | | **PSTN ingress via Twilio** | Twilio trunk dials `sip.yourdomain.com;transport=tcp` → Sayna validates `room_prefix` and source IPs → auto-provisioned LiveKit trunk/dispatch routes the call → `/livekit/token` lets agents join from browsers while SIP hooks notify backend systems. | ## Operational checklist * **Dependencies** – Outbound HTTPS to providers + LiveKit; inbound TCP from carrier IPs when SIP is enabled. * **Scaling** – `/ws` sessions are stateful. Run multiple Sayna instances behind a load balancer (with sticky sessions if the proxy terminates WebSockets). * **Observability** – Monitor `ready` vs `error` rates, STT latency, cache hit ratios, SIP provisioning logs, and webhook forwarding success. * **Security** – Use `AUTH_REQUIRED=true` plus API secrets or delegated JWT to protect REST + WebSocket traffic, and keep SIP hooks HTTPS-only. With this architecture in mind you can choose the right combination of WebSocket, REST, LiveKit, and SIP capabilities for your deployment before implementing the finer details. # Authentication Source: https://docs.sayna.ai/guides/authentication Protect Sayna endpoints with either a shared secret or delegated JWT validation. Sayna supports two authentication strategies. Choose the one that matches your deployment needs, or enable both. When both are configured Sayna first checks the API secret, then falls back to delegated JWT validation. Protected HTTP endpoints accept the authentication token via either method: * **Header**: `Authorization: Bearer ` * **Query parameter**: `?api_key=` Both API Secret mode and JWT mode use the same token extraction behavior. ## Token precedence and fallback When both an `Authorization` header and an `api_key` query parameter are present, Sayna evaluates them in this order: 1. The `Authorization` header is evaluated first. 2. If the header format is invalid, the server falls back to the `api_key` query parameter. If neither source provides a usable token, the request is rejected with `missing_auth_header`. ## Quick summary | Mode | When to use | Highlights | | ---------------------- | --------------------------------------------- | --------------------------------------------------------------------------------------------------------- | | **API secret** | Single-tenant deployments or trusted networks | Lowest latency, no external service, bearer-token comparison against `AUTH_API_SECRET`. | | **JWT + auth service** | Multi-tenant or context-aware authorization | Sayna signs the entire request payload, calls out to your service, and trusts the HTTP status you return. | Toggle auth with the `AUTH_REQUIRED` environment variable. When it's `false`, all endpoints accept unauthenticated requests. ## Option A — API secret authentication ### Setup steps 1. Generate a long random secret. ```bash theme={null} openssl rand -base64 32 ``` 2. Set the environment variables: ```bash theme={null} AUTH_REQUIRED=true AUTH_API_SECRET=your-generated-secret ``` 3. Clients send the secret as a bearer token in the header or as a query parameter: ```bash theme={null} # Using Authorization header (recommended) curl -X POST http://localhost:3001/speak \ -H "Authorization: Bearer your-generated-secret" \ -H "Content-Type: application/json" \ -d '{"text": "Hello world"}' # Using query parameter curl -X POST "http://localhost:3001/speak?api_key=your-generated-secret" \ -H "Content-Type: application/json" \ -d '{"text": "Hello world"}' ``` ### Security notes * Use at least 32 random bytes; rotate periodically and never commit secrets to VCS. * Always terminate TLS before traffic reaches Sayna so the bearer token stays encrypted in transit. * Pair with IP allowlists when you use this mode for back-office tools. ## Option B — Delegated JWT authentication API secret not enough? Let your own service validate tokens and return `200`/`401` decisions. ### 1. Generate signing keys ```bash theme={null} # RSA openssl genrsa -out auth_private_key.pem 2048 openssl rsa -in auth_private_key.pem -pubout -out auth_public_key.pem chmod 600 auth_private_key.pem chmod 644 auth_public_key.pem # or ECDSA openssl ecparam -genkey -name prime256v1 -noout -out auth_private_key.pem openssl ec -in auth_private_key.pem -pubout -out auth_public_key.pem ``` ### 2. Configure Sayna ```bash theme={null} AUTH_REQUIRED=true AUTH_SERVICE_URL=https://your-auth-service.com/auth AUTH_SIGNING_KEY_PATH=/path/to/auth_private_key.pem AUTH_TIMEOUT_SECONDS=5 ``` ### 3. Implement the auth service Your service must: 1. Accept `POST` requests whose body is the JWT Sayna generated. 2. Verify the JWT signature using the public key (RS256 or ES256). 3. Validate the extracted bearer token and any contextual data. 4. Return `200 OK` (allow) or `401 Unauthorized` (deny). Other 4xx map to `401`, 5xx become `502`, and timeouts surface as `503` upstream. ```javascript theme={null} const express = require('express'); const jwt = require('jsonwebtoken'); const fs = require('fs'); const app = express(); const publicKey = fs.readFileSync('auth_public_key.pem'); app.post('/auth', express.text(), (req, res) => { try { const payload = jwt.verify(req.body, publicKey, { algorithms: ['RS256', 'ES256'] }); const isValid = validateToken(payload.token); if (isValid) { res.status(200).send('OK'); } else { res.status(401).send('Invalid token'); } } catch (error) { res.status(401).send('JWT verification failed'); } }); app.listen(3000); ``` ## Environment variables | Variable | Required | Default | Description | | ----------------------- | ----------- | ------- | ------------------------------------------------- | | `AUTH_REQUIRED` | No | `false` | Enable or disable authentication middleware. | | `AUTH_API_SECRET` | Conditional | – | Shared secret for API secret auth. | | `AUTH_SERVICE_URL` | Conditional | – | External auth service endpoint (JWT mode). | | `AUTH_SIGNING_KEY_PATH` | Conditional | – | Path to private key used to sign the JWT payload. | | `AUTH_TIMEOUT_SECONDS` | No | `5` | Timeout for auth service requests. | When `AUTH_REQUIRED=true` you must specify either `AUTH_API_SECRET` or both `AUTH_SERVICE_URL` and `AUTH_SIGNING_KEY_PATH`. You can configure both to let Sayna short-circuit known service-to-service traffic with the secret and route user traffic through the JWT flow. ## JWT payload schema (delegated mode) ```json theme={null} { "sub": "sayna-auth", "iat": 1234567890, "exp": 1234568190, "auth_data": { "token": "extracted-token-from-header-or-query", "request_body": {"text": "request body as JSON"}, "request_headers": { "content-type": "application/json", "user-agent": "client-agent" }, "request_path": "/speak", "request_method": "POST" } } ``` * `sub`: Always `sayna-auth` so your service knows who issued the JWT. * `iat` / `exp`: Issued-at plus 5-minute expiration. * `auth_data.token`: The extracted usable token, resolved from the `Authorization` header or the `api_key` query parameter (following the precedence rule above). * `auth_data.request_body`: JSON payload of the HTTP request. * `auth_data.request_headers`: Filtered headers (excludes `authorization`, `cookie`, `x-forwarded-*`, `x-sayna-*`, `host`, `x-real-ip`). * `auth_data.request_path` / `request_method`: Full request context for policy decisions. ### Verification checklist ```python theme={null} def verify_auth_request(jwt_string, public_key): payload = jwt.decode(jwt_string, public_key, algorithms=['RS256', 'ES256']) if payload['sub'] != 'sayna-auth': return 401, 'Invalid JWT subject' now = int(time.time()) if abs(now - payload['iat']) > 60: return 401, 'JWT too old' auth_data = payload['auth_data'] bearer_token = auth_data['token'] if not is_valid_token(bearer_token): return 401, 'Invalid bearer token' return 200, 'OK' ``` ## Protected endpoints When `AUTH_REQUIRED=true` the following endpoints require authentication: * `POST /speak` * `GET /voices` * `POST /livekit/token` * `GET /livekit/rooms` * `GET /livekit/rooms/{room_name}` * `DELETE /livekit/participant` * `POST /livekit/participant/mute` * `GET /recording/{stream_id}` * `POST /sip/call` * `GET /sip/hooks` * `POST /sip/hooks` * `DELETE /sip/hooks` * `POST /sip/transfer` Public endpoints today: * `GET /` (health) * `GET /ws` (WebSocket handshake — see the WebSocket Auth roadmap below) ## Room-scoped authorization Beyond authentication, room-scoped endpoints enforce ownership via `metadata.auth_id`: | Endpoint | Ownership check | | -------------------------------- | ------------------------------------------------------------------------------------------ | | `POST /livekit/token` | Creates room with `metadata.auth_id` if missing; returns `403` if owned by another tenant. | | `GET /livekit/rooms` | Filters to rooms matching `metadata.auth_id`. | | `GET /livekit/rooms/{room_name}` | Returns `404` if `metadata.auth_id` doesn't match. | | `DELETE /livekit/participant` | Returns `404` if `metadata.auth_id` doesn't match. | | `POST /livekit/participant/mute` | Returns `404` if `metadata.auth_id` doesn't match. | | `POST /sip/call` | Creates room with `metadata.auth_id`; returns `404` if owned by another tenant. | | `POST /sip/transfer` | Returns `404` if `metadata.auth_id` doesn't match. | Room names are no longer prefixed or modified. Access control is enforced entirely through the `metadata.auth_id` field stored in room metadata. ## WebSocket authentication status WebSocket auth is not implemented yet. The open tasks from the design document: 1. Authenticate during the HTTP upgrade by reading query parameters or headers. 2. Require an auth payload inside the first `config` message. 3. Or leave `/ws` public but scope LiveKit mirroring to trusted rooms. Today, Sayna runs with **Option C** (no WebSocket auth). Use network isolation or API Gateways until JWT enforcement ships. ## Usage examples ```bash theme={null} # API secret — header curl -X GET http://localhost:3001/voices \ -H "Authorization: Bearer $AUTH_API_SECRET" # API secret — query parameter curl -X GET "http://localhost:3001/voices?api_key=$AUTH_API_SECRET" # JWT-based — header curl -X POST http://localhost:3001/speak \ -H "Authorization: Bearer user-jwt-token" \ -H "Content-Type: application/json" \ -d '{"text": "Different user"}' # JWT-based — query parameter curl -X POST "http://localhost:3001/speak?api_key=user-jwt-token" \ -H "Content-Type: application/json" \ -d '{"text": "Different user"}' ``` ## Client guidance **Recommended default**: Use the `Authorization: Bearer ` header whenever possible. Header-based auth keeps tokens out of URL strings, server logs, and browser history. **When to use query parameter auth**: The `?api_key=` query parameter is practical in environments where adding custom headers is difficult — for example, browser redirects, webhook callbacks from third-party services, or server-sent event streams. Tokens passed as query parameters can be logged in URL logs, proxy access logs, and analytics tooling. Always use HTTPS and avoid logging full URLs when query auth is used. ## Backward compatibility * Existing header-based clients continue to work unchanged. * Query-based auth is additive and non-breaking. * Clients currently sending an invalid `Authorization` header alongside a valid `api_key` query parameter will now authenticate successfully via fallback. ## Scope clarification This dual-input auth behavior applies to **protected HTTP endpoints only**. It does not change: * The **WebSocket auth model** (see [WebSocket authentication status](#websocket-authentication-status) below). * The **LiveKit webhook signature verification flow**, which uses its own signing mechanism independent of bearer tokens. **Provider-level credentials** are separate from server-level authentication. In addition to the API secret and JWT strategies described above, Sayna supports per-session and per-request provider credential overrides via the `auth` field in STT/TTS config objects. This allows multi-tenant clients to supply their own Deepgram, ElevenLabs, Cartesia, Google, or Azure credentials without changing server configuration. See the [WebSocket guide](/guides/websocket#provider-auth-overrides) for details. ## Error responses ```json theme={null} { "error": "error_code", "message": "Human-readable error message" } ``` | Error code | HTTP status | Description | | -------------------------- | ----------- | ------------------------------------------------------------------------------------------------ | | `missing_auth_header` | 401 | No usable token was found in either the `Authorization` header or the `api_key` query parameter. | | `invalid_auth_header` | 401 | Header format is invalid and no valid `api_key` fallback was provided. | | `unauthorized` | 401 | Token validation failed. | | `auth_service_error` | 401 or 502 | Auth service returned 4xx/5xx. | | `auth_service_unavailable` | 503 | Auth service unreachable or timed out. | | `config_error` | 500 | Misconfigured auth flags/keys. | | `jwt_signing_error` | 500 | Failed to sign JWT payload. | ### Mapping auth service responses | Auth service status | Sayna response | Meaning | | ----------------------- | ------------------------- | ------------------------------------------------- | | `200 OK` | `200 OK` | Token valid; request proceeds. | | `401 Unauthorized` | `401 Unauthorized` | Invalid token; client should refresh credentials. | | Other `4xx` | `401 Unauthorized` | Client error mapped to unauthorized. | | `5xx` | `502 Bad Gateway` | Temporary auth service failure. | | Timeout / network error | `503 Service Unavailable` | Auth service unreachable. | ## Security considerations * **Private keys**: Store private keys with `chmod 600`, never commit them, and rotate periodically. * **Network security**: Run Sayna + auth service over HTTPS/TLS. Consider mutual TLS between the two if you run them across trust zones. * **Token validation**: Reject replayed JWTs by checking `iat`; combine with short expirations. * **Error handling**: Return generic error bodies to clients but log detailed errors internally for auditing. * **Replay protection**: Compare `iat` against `now` (±60 seconds) before trusting the payload. Always verify the JWT signature **and** the embedded request hash before trusting delegated responses. Skipping either check makes it possible to replay tampered requests. # Deployment guide Source: https://docs.sayna.ai/guides/deployment Package Sayna as a container and run it alongside LiveKit. Sayna ships as a single Axum binary that runs anywhere you can schedule containers. The sections below walk through the recommended workflow for container builds, Docker Compose, and Kubernetes. ## 1. Prerequisites * **LiveKit cluster** reachable from the Sayna pod/container (LAN or VPC). Set `LIVEKIT_URL` to the internal address and `LIVEKIT_PUBLIC_URL` to what clients should use. * **Provider credentials** for the STT/TTS services you plan to use: * `DEEPGRAM_API_KEY` for Deepgram STT/TTS * `ELEVENLABS_API_KEY` for ElevenLabs TTS * These server-level credentials serve as defaults. Clients can optionally override them per session or per request using the `auth` field in STT/TTS config objects. See the [WebSocket guide](/guides/websocket#provider-auth-overrides). * Optional: S3-compatible bucket for LiveKit recording egress (`RECORDING_S3_*`). * Optional: Authentication settings from the [Authentication guide](/guides/authentication). * Persistent volume (or host path) for `CACHE_PATH` when you want cached audio and turn-detector assets to survive container restarts. ## 2. Build the container image Use the provided multi-stage `Dockerfile` (Rust toolchain + runtime slim image): ```bash theme={null} docker build -t sayna:latest . ``` Key flags: * `--build-arg RUST_VERSION=1.75.0` pins the toolchain when you need reproducibility. * `sayna init` runs during the image build to pre-download turn-detection assets when `CACHE_PATH` is set. Re-run `sayna init` at runtime if you mount a fresh cache volume. * Sayna listens on port `3001` by default; override via `-e PORT=XXXX`. ## 3. Runtime environment | Variable | Purpose | Example | | ---------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------ | | `HOST` | Bind address inside the container. | `0.0.0.0` | | `PORT` | Axum listener port. | `3001` | | `CACHE_PATH` | Directory that stores cached audio and turn-detect assets. | `/data/cache` | | `DEEPGRAM_API_KEY` | Enables Deepgram STT/TTS. | `dg-secret` | | `ELEVENLABS_API_KEY` | Enables ElevenLabs TTS. | `el-secret` | | `LIVEKIT_URL` | Server-to-server WebSocket URL (internal). | `ws://livekit:7880` | | `LIVEKIT_PUBLIC_URL` | URL clients should dial. | `https://rtc.yourdomain.com` | | `LIVEKIT_API_KEY` / `LIVEKIT_API_SECRET` | Credentials used to mint `/livekit/token` responses and join rooms. | `lk_key` / `lk_secret` | | `RECORDING_S3_*` | Bucket configuration for LiveKit recordings. | bucket, region, endpoint, access key, secret key | | `AUTH_*` | Optional shared-secret or JWT auth; see [Authentication](/guides/authentication). | – | ## 4. Local Docker run ```bash theme={null} docker run --rm \ -p 3001:3001 \ -e HOST=0.0.0.0 \ -e PORT=3001 \ -e CACHE_PATH=/data/cache \ -e DEEPGRAM_API_KEY=dg-secret \ -e ELEVENLABS_API_KEY=el-secret \ -e LIVEKIT_URL=ws://livekit:7880 \ -e LIVEKIT_PUBLIC_URL=https://rtc.localhost \ -e LIVEKIT_API_KEY=lk_key \ -e LIVEKIT_API_SECRET=lk_secret \ -v sayna-cache:/data/cache \ sayna:latest ``` Mounting `sayna-cache` ensures cached voices and turn detection assets persist between runs. ## 5. Docker Compose example ```yaml theme={null} version: "3.9" services: livekit: image: livekit/livekit-server:latest environment: - LIVEKIT_KEYS=lk_key:lk_secret ports: - "7880:7880" - "7881:7881" sayna: image: sayna:latest depends_on: - livekit ports: - "3001:3001" environment: HOST: 0.0.0.0 PORT: 3001 CACHE_PATH: /data/cache DEEPGRAM_API_KEY: ${DEEPGRAM_API_KEY} ELEVENLABS_API_KEY: ${ELEVENLABS_API_KEY} LIVEKIT_URL: ws://livekit:7880 LIVEKIT_PUBLIC_URL: https://rtc.example.com LIVEKIT_API_KEY: lk_key LIVEKIT_API_SECRET: lk_secret RECORDING_S3_BUCKET: sayna-egress RECORDING_S3_REGION: us-east-1 RECORDING_S3_ENDPOINT: https://s3.amazonaws.com RECORDING_S3_ACCESS_KEY: ${S3_ACCESS_KEY} RECORDING_S3_SECRET_KEY: ${S3_SECRET_KEY} volumes: - sayna-cache:/data/cache volumes: sayna-cache: {} ``` Compose networking keeps `LIVEKIT_URL=ws://livekit:7880` internal while `LIVEKIT_PUBLIC_URL` remains externally accessible. ## 6. Kubernetes deployment ```yaml theme={null} apiVersion: apps/v1 kind: Deployment metadata: name: sayna spec: replicas: 2 selector: matchLabels: app: sayna template: metadata: labels: app: sayna spec: containers: - name: sayna image: ghcr.io/your-org/sayna:latest ports: - containerPort: 3001 envFrom: - secretRef: name: sayna-secrets - configMapRef: name: sayna-config volumeMounts: - name: cache mountPath: /data/cache volumes: - name: cache persistentVolumeClaim: claimName: sayna-cache-pvc --- apiVersion: v1 kind: Service metadata: name: sayna spec: selector: app: sayna ports: - name: http port: 3001 targetPort: 3001 type: ClusterIP ``` Recommended `ConfigMap` snippet: ```yaml theme={null} apiVersion: v1 kind: ConfigMap metadata: name: sayna-config data: HOST: "0.0.0.0" PORT: "3001" CACHE_PATH: "/data/cache" LIVEKIT_URL: "ws://livekit.livekit.svc.cluster.local:7880" LIVEKIT_PUBLIC_URL: "https://rtc.example.com" ``` Store `DEEPGRAM_API_KEY`, `ELEVENLABS_API_KEY`, `LIVEKIT_API_KEY`, `LIVEKIT_API_SECRET`, and S3 credentials inside `sayna-secrets`. ## 7. LiveKit configuration checklist 1. **Networking** – ensure the Sayna pod can reach the LiveKit signaling endpoint specified in `LIVEKIT_URL` (Compose service name, Kubernetes service DNS, etc.). 2. **Credentials** – set `LIVEKIT_API_KEY` / `LIVEKIT_API_SECRET`. Sayna uses these to mint: * Agent tokens during the WebSocket `config` workflow (`livekit` block). * User tokens returned by the `/livekit/token` REST endpoint. 3. **Client workflow** – a typical `config` message includes: ```json theme={null} { "type": "config", "stream_id": "support-room-42-2024-01-31", "audio": true, "stt_config": { "provider": "deepgram", "language": "en-US", "sample_rate": 16000 }, "tts_config": { "provider": "deepgram", "voice_id": "aura-aria" }, "livekit": { "room_name": "support-room-42", "enable_recording": true, "sayna_participant_identity": "sayna-ai", "sayna_participant_name": "Sayna AI", "listen_participants": ["agent-1", "customer-42"] } } ``` When `enable_recording=true`, LiveKit needs a valid egress target. Set a session-level `stream_id` to control the `{server_prefix}/{stream_id}/audio.ogg` path, or omit it to let the server generate one. Ensure `RECORDING_S3_*` or other LiveKit egress settings are populated. # LiveKit room management Source: https://docs.sayna.ai/guides/livekit-room-management Manage LiveKit rooms and participants through Sayna's authenticated REST endpoints. Sayna exposes a thin LiveKit management layer so you can list rooms, inspect participants, and moderate sessions without calling the LiveKit admin API directly. This keeps LiveKit credentials server-side and applies the same auth rules you already use across Sayna. When `AUTH_REQUIRED=true`, all endpoints below require a token via the `Authorization: Bearer ` header or the `api_key` query parameter. The header is recommended by default. ## Why Sayna wraps LiveKit * Prevents exposing LiveKit API keys or admin endpoints to client applications. * Enforces Sayna authentication and authorization for every management call. * Keeps multi-tenant isolation consistent across REST and WebSocket flows. ## Published audio tracks When a WebSocket session is audio-enabled and joins a LiveKit room, the Sayna agent participant publishes synthesized speech on an audio track named `"tts-audio"`. If that session's `config` message also includes a [`loading_audio`](/guides/websocket#loading_audio-configuration) object, the agent publishes a **second** audio track named `"loading-audio"` carrying the loading-indicator sound. | Track name | Carries | | ----------------- | ------------------------------------------------------------------------- | | `"tts-audio"` | Synthesized speech (text-to-speech output). | | `"loading-audio"` | The loading-indicator clip, looped while the calling application is busy. | The two tracks are independent and can be audible at the same time. LiveKit client SDKs automatically play every subscribed audio track, so participants hear both without any extra client-side handling. Because `"loading-audio"` is a real published track, it is included in room-composite egress recordings alongside `"tts-audio"`. This is correct behavior — the recording faithfully reflects what the human participant heard. ## Room ownership and access control Room access is controlled via the `metadata.auth_id` field stored in room metadata. When authentication is enabled: * **Room creation**: When you request a token for a room that doesn't exist, Sayna creates it and sets `metadata.auth_id` to your tenant ID. * **Room access**: All room-scoped operations verify that `room.metadata.auth_id` matches your authenticated `auth.id`. * **Access denied**: Unauthorized access returns `404 Not Found` (masked for security) or `403 Forbidden` depending on the operation. Room names are no longer modified or prefixed. You send and receive clean room names exactly as specified. ### Backward compatibility When `auth.id` is absent (unauthenticated mode), all rooms are accessible. This maintains compatibility with deployments that don't require authentication. ## Endpoint overview | Endpoint | Use case | | -------------------------------- | ------------------------------------------------------------------------------------------------------ | | `POST /livekit/token` | Mint participant tokens and create rooms. [API reference](/api-reference/endpoint/livekit-token) | | `GET /livekit/rooms` | List rooms for the current tenant. [API reference](/api-reference/endpoint/livekit-rooms) | | `GET /livekit/rooms/{room_name}` | Inspect room details and participants. [API reference](/api-reference/endpoint/livekit-room) | | `DELETE /livekit/participant` | Remove a participant from a room. [API reference](/api-reference/endpoint/livekit-participant) | | `POST /livekit/participant/mute` | Mute or unmute a participant track. [API reference](/api-reference/endpoint/livekit-participant-mute) | | `POST /sip/call` | Initiate an outbound SIP call. [API reference](/api-reference/endpoint/sip-call) | | `POST /sip/transfer` | Transfer a SIP participant to a new destination. [API reference](/api-reference/endpoint/sip-transfer) | ## Typical flow Call `POST /livekit/token` with your room name. If the room doesn't exist, Sayna creates it and sets `metadata.auth_id` to your tenant ID before returning the token. Call `GET /livekit/rooms` to discover active rooms. Only rooms with matching `metadata.auth_id` are returned. Use `GET /livekit/rooms/{room_name}` to fetch participant identities and metadata. Disconnect a participant with `DELETE /livekit/participant` or mute a track with `POST /livekit/participant/mute`. Initiate outbound calls with `POST /sip/call` or transfer existing SIP participants with `POST /sip/transfer`. ## Error handling Room-scoped operations return specific errors for access control: | Status | Meaning | | --------------------------- | ------------------------------------------------------------------------- | | `403 Forbidden` | Room exists with a different tenant's `auth_id` (token endpoint only). | | `404 Not Found` | Room not found or access denied (masked for security on other endpoints). | | `500 Internal Server Error` | LiveKit not configured or operation failed. | When you receive a `403` on token generation, the room already exists and is owned by another tenant. Choose a different room name or contact the room owner. Removing a participant does not revoke their LiveKit token. If you need to prevent rejoin, issue short-lived tokens and avoid re-minting them after removal. # Operations & best practices Source: https://docs.sayna.ai/guides/operations Tips for running Sayna in production clusters. ## Runtime tuning * **Reuse `tts_config` hashes**: `VoiceManager` caches rendered audio per text + config hash, so reusing configs dramatically reduces provider round-trips. * **Disable audio when needed**: Set `audio=false` in the `config` message to use LiveKit data relaying without spinning up STT/TTS providers. * **Balance CPU vs. quality**: `noise-filter` improves transcripts but costs CPU; toggle the feature flag when ultra-low latency is more important than denoising. * **Persist caches**: Mount `CACHE_PATH` to a durable volume if you want previously synthesized clips and turn-detect assets to survive restarts. ## Observability & testing * Use the integration tests in `tests/` (e.g., `tests/ws_tests.rs`) as references when extending message formats or LiveKit behavior. * Emit application metrics around provider errors and queue depth to quickly detect throttling. * Enable structured logging inside WebSocket handlers so you can correlate STT/TTS lifecycle events with LiveKit callbacks. ## Release hygiene * Regenerate the OpenAPI file with `cargo run --features openapi -- openapi -o docs/openapi.yaml` whenever you tweak request or response schemas. * Keep the documentation and server version in lockstep; expose the git SHA or semver string via `/` so probes can verify deployments. * Rotate provider credentials and authentication keys as part of your deployment pipelines; the [Authentication guide](/guides/authentication) documents the required env vars. ## Operational playbook Many outages boil down to LiveKit connectivity or provider rate limits. Monitor those dependencies explicitly and surface their status in your dashboards. 1. **Circuit breakers**: Treat provider 5xx responses as signals to backoff and fall back to cached content when possible. 2. **Traffic shaping**: Consider per-tenant rate limits enforced inside your JWT auth service so Sayna sees predictable load. 3. **WebSocket health**: Alert on connection churn, repeated `error` frames, or clients that never send `config`. 4. **LiveKit drift**: Keep Sayna and LiveKit clocks in sync; recording requests rely on accurate timestamps. # REST API surface Source: https://docs.sayna.ai/guides/rest-api Health checks, catalog discovery, TTS synthesis, LiveKit room controls, and SIP utilities. Sayna exposes a compact set of HTTP endpoints that reuse the same providers and caches that power the streaming stack. Use the interactive playground inside the [API reference](/api-reference/introduction) for request-by-request schemas and try-it-out support. If you need tenant-scoped room management (listing rooms, inspecting participants, or moderating LiveKit sessions), see the [Livekit Room Management guide](/guides/livekit-room-management). Authentication is optional. Enable it through the [Authentication guide](/guides/authentication) if you need shared secrets or delegated JWT validation. Want idiomatic clients? Install one of the [Sayna SDKs](/sdks/js) to reuse the snippets shown below. SDK examples assume you have already instantiated a `client` (see the SDK guides for setup) and are showing only the method call relevant to each endpoint. ## `GET /` – health check * **Purpose**: returns `{ "status": "ok" }` when the server and dependencies are alive. * **Status codes**: always `200 OK` when the Axum router is reachable. * **Usage**: liveness/readiness probes and smoke tests after deployments. ```bash theme={null} curl https://api.sayna.ai/ # => {"status":"ok"} ``` ```ts theme={null} const health = await client.health(); console.log(health.status); ``` ```python theme={null} from sayna_client import SaynaClient, STTConfig, TTSConfig client = SaynaClient( url="https://api.sayna.ai", stt_config=STTConfig(provider="deepgram", model="nova-2"), tts_config=TTSConfig(provider="elevenlabs", voice_id="21m00Tcm4TlvDq8ikWAM"), ) health = await client.health() print(health.status) ``` ## `GET /voices` – provider catalog | Detail | Description | | -------------- | ---------------------------------------------------------------------- | | Request body | none | | Authentication | Required when `AUTH_REQUIRED=true` | | Success | `200 OK` with provider metadata and voice options | | Failure | `401 Unauthorized` when auth fails, `500` for upstream provider errors | Response schema mirrors each provider's capabilities, including languages, sample rates, and optional tags. Use the payload to drive voice pickers inside your product. ```bash theme={null} curl https://api.sayna.ai/voices | jq '.voices[0]' ``` ```ts theme={null} const voices = await client.getVoices(); console.log(voices.deepgram?.[0]); ``` ```python theme={null} voices = await client.get_voices() print(next(iter(voices.values()))[0]) ``` ## `POST /speak` – one-shot synthesis | Field | Type | Required | Description | | -------------------------- | ------- | -------- | ------------------------------------------------------------------------------------------------------------------- | | `text` | string | Yes | Text to convert into audio | | `tts_config` | object | Yes | TTS configuration (same schema as the WebSocket `tts_config`) | | `tts_config.provider` | string | Yes | Provider slug (e.g., `deepgram`, `elevenlabs`, `cartesia`, `azure`, `google`) | | `tts_config.model` | string | Yes | Model name for the TTS provider | | `tts_config.voice_id` | string | No | Voice from `/voices`; provider default when omitted | | `tts_config.audio_format` | string | No | Audio format preference (e.g., `linear16`, `mp3`) | | `tts_config.sample_rate` | integer | No | Sample rate in Hz | | `tts_config.speaking_rate` | number | No | Speaking rate (0.25–4.0, default 1.0) | | `tts_config.auth` | object | No | Per-request provider credential override (see [Provider auth overrides](/guides/websocket#provider-auth-overrides)) | * **Request**: JSON body plus optional auth via `Authorization` header or `api_key` query parameter. * **Response**: `200 OK` with raw `audio/pcm` bytes plus `x-audio-format` and `x-sample-rate` response headers. * **Errors**: `400` when `text` is empty, `500` for provider failures or missing credentials. ```bash theme={null} curl -X POST https://api.sayna.ai/speak \ -H "Content-Type: application/json" \ -d '{ "text": "Welcome to Sayna", "tts_config": { "provider": "deepgram", "model": "aura-asteria-en" } }' \ --output audio.pcm ``` ```bash theme={null} # With per-request provider credentials curl -X POST https://api.sayna.ai/speak \ -H "Content-Type: application/json" \ -d '{ "text": "Hello from Sayna", "tts_config": { "provider": "elevenlabs", "model": "eleven_flash_v2_5", "voice_id": "voice_id_here", "auth": { "api_key": "your-elevenlabs-key" } } }' \ --output audio.pcm ``` ```ts theme={null} const audioBuffer = await client.speakRest("Welcome to Sayna", { provider: "deepgram", model: "aura-asteria-en", voice_id: "aura-asteria-en", }); console.log(`Received ${audioBuffer.byteLength} bytes`); ``` ```ts theme={null} // With per-request provider credentials const audioBuffer = await client.speakRest("Welcome to Sayna", { provider: "elevenlabs", model: "eleven_flash_v2_5", voice_id: "voice_id_here", auth: { api_key: "your-elevenlabs-key" }, }); ``` ```python theme={null} audio_bytes, headers = await client.speak_rest( "Welcome to Sayna", TTSConfig(provider="deepgram", voice_id="aura-asteria-en"), ) print(len(audio_bytes), "bytes of", headers.get("Content-Type")) ``` ```python theme={null} # With per-request provider credentials audio_bytes, headers = await client.speak_rest( "Welcome to Sayna", TTSConfig( provider="elevenlabs", model="eleven_flash_v2_5", voice_id="voice_id_here", auth={"api_key": "your-elevenlabs-key"}, ), ) ``` ## `POST /livekit/token` – participant tokens | Field | Type | Description | | ---------------------- | ------ | -------------------------------------- | | `room_name` | string | Room to join or create | | `participant_name` | string | Display name shown inside LiveKit | | `participant_identity` | string | Stable identity string for permissions | Returns: | Field | Type | Description | | ---------------------- | ------ | -------------------------------------- | | `token` | string | Signed LiveKit JWT for the participant | | `room_name` | string | Echoes the requested room | | `participant_identity` | string | Echo of the requested identity | | `livekit_url` | string | Client-facing LiveKit URL from config | When authentication is enabled, this endpoint creates the room if it doesn't exist and sets `metadata.auth_id` for tenant isolation. * **Errors**: `400` when any field is empty, `403` when the room exists with a different tenant's `auth_id`, `500` when LiveKit credentials are misconfigured. * **Typical flow**: once a WebSocket session advertises LiveKit settings in the `config` message, call this REST endpoint from your control plane to mint attendee tokens. ```bash theme={null} curl -X POST https://api.sayna.ai/livekit/token \ -H "Content-Type: application/json" \ -d '{ "room_name": "support-42", "participant_name": "alex", "participant_identity": "alex-support" }' ``` ```ts theme={null} const tokenInfo = await client.getLiveKitToken( "support-42", "alex", "alex-support" ); console.log(tokenInfo.token, tokenInfo.livekit_url); ``` ```python theme={null} token = await client.get_livekit_token("support-42", "alex", "alex-support") print(token.token, token.livekit_url) ``` ## `GET /recording/{stream_id}` – download session audio | Detail | Description | | -------------- | -------------------------------------------------------------------------------------------------------------------- | | Path param | `stream_id` from the WebSocket `ready` message (or the value you provided). Empty values, `..`, or `/` are rejected. | | Authentication | Required when `AUTH_REQUIRED=true` | | Success | `200 OK` with `audio/ogg` body and `Content-Disposition: attachment; filename="{stream_id}.ogg"` | | Failure | `400` invalid `stream_id`, `404` recording missing, `503` storage not configured or unavailable | Recording files live at `{recording_s3_prefix}/{stream_id}/audio.ogg` when `livekit.enable_recording=true` and storage credentials are set. ```bash theme={null} # Download and save as .ogg curl -OJ https://api.sayna.ai/recording/support-call-789 ``` ```ts theme={null} import { promises as fs } from "fs"; const streamId = client.streamId; // from ready() const audio = await client.getRecording(streamId!); await fs.writeFile(`${streamId}.ogg`, Buffer.from(audio)); ``` ```python theme={null} stream_id = client.received_stream_id audio_bytes, headers = await client.get_recording(stream_id) with open(f"{stream_id}.ogg", "wb") as f: f.write(audio_bytes) ``` ## `POST /sip/call` – initiate SIP call | Field | Type | Required | Description | | ---------------------- | ------ | -------- | ---------------------------------------------------------------- | | `room_name` | string | Yes | The LiveKit room to connect the call to | | `participant_name` | string | Yes | Display name for the SIP participant in the room | | `participant_identity` | string | Yes | Unique identity for the SIP participant | | `from_phone_number` | string | Yes | Caller ID phone number (must be configured in your SIP provider) | | `to_phone_number` | string | Yes | Destination phone number to dial | | `sip` | object | No | Per-request SIP configuration overrides (see below) | The optional `sip` object allows overriding global SIP configuration on a per-request basis. This is useful when you need to use different SIP providers or credentials for specific calls. | Field | Type | Description | | ---------------------- | ------------ | ------------------------------------------------------------------ | | `sip.outbound_address` | string\|null | SIP server address override. Format: `hostname` or `hostname:port` | | `sip.auth_username` | string\|null | SIP authentication username override | | `sip.auth_password` | string\|null | SIP authentication password override | * **Request**: JSON body plus optional auth via `Authorization` header or `api_key` query parameter. * **Response**: `200 OK` with call status, room name, participant identity, participant ID, and SIP call ID. * **Errors**: `400` when phone number is invalid or required fields are empty, `404` when room exists with a different tenant's `auth_id`, `500` when LiveKit is not configured, outbound address is missing, or call fails. Phone numbers support international format (`+1234567890`), national format (`07123456789`), or internal extensions (`1234`). See the [API reference](/api-reference/endpoint/sip-call) for detailed schema information. ```bash theme={null} # Basic call (uses global SIP configuration) curl -X POST https://api.sayna.ai/sip/call \ -H "Content-Type: application/json" \ -d '{ "room_name": "call-room-123", "participant_name": "John Doe", "participant_identity": "caller-456", "from_phone_number": "+15105550123", "to_phone_number": "+15551234567" }' ``` ```bash theme={null} # With per-request SIP configuration overrides curl -X POST https://api.sayna.ai/sip/call \ -H "Content-Type: application/json" \ -d '{ "room_name": "call-room-123", "participant_name": "John Doe", "participant_identity": "caller-456", "from_phone_number": "+15105550123", "to_phone_number": "+15551234567", "sip": { "outbound_address": "sip.provider.com:5060", "auth_username": "user123", "auth_password": "secret456" } }' ``` The `sipCall` method is available in SDK version 0.3.0 and later. ```ts theme={null} const result = await client.sipCall({ roomName: "call-room-123", participantName: "John Doe", participantIdentity: "caller-456", fromPhoneNumber: "+15105550123", toPhoneNumber: "+15551234567", }); console.log(result.sipCallId, result.participantId); ``` ```ts theme={null} // With per-request SIP configuration overrides const result = await client.sipCall({ roomName: "call-room-123", participantName: "John Doe", participantIdentity: "caller-456", fromPhoneNumber: "+15105550123", toPhoneNumber: "+15551234567", sip: { outboundAddress: "sip.provider.com:5060", authUsername: "user123", authPassword: "secret456", }, }); ``` The `sip_call` method is available in SDK version 0.3.0 and later. ```python theme={null} result = await client.sip_call( room_name="call-room-123", participant_name="John Doe", participant_identity="caller-456", from_phone_number="+15105550123", to_phone_number="+15551234567", ) print(result.sip_call_id, result.participant_id) ``` ```python theme={null} # With per-request SIP configuration overrides result = await client.sip_call( room_name="call-room-123", participant_name="John Doe", participant_identity="caller-456", from_phone_number="+15105550123", to_phone_number="+15551234567", sip={ "outbound_address": "sip.provider.com:5060", "auth_username": "user123", "auth_password": "secret456", }, ) ``` ## Cache-aware behavior * `/speak` reuses cached synthesis when both the `text` and `tts_config` hash match a previous request and caching is enabled. * Cache assets live under `CACHE_PATH`; mount a persistent volume in production if you want to avoid cold starts. * Clear server caches when rotating provider credentials or when you change voice defaults that affect TTS hashes. # SIP configuration Source: https://docs.sayna.ai/guides/sip Opt into SIP-aware routing, provisioning, and webhook forwarding for LiveKit calls. Sayna treats SIP support as a fully optional module. When the `sip` block is absent, no trunks are provisioned, webhook forwarding is skipped, and the runtime avoids emitting SIP-specific logs. Configure the section below only when you need SIP-enabled LiveKit rooms. LiveKit SIP support requires valid `LIVEKIT_API_KEY` and `LIVEKIT_API_SECRET` values. Provisioning is idempotent—restarts never duplicate trunks or dispatch rules. ## Configuration methods ### YAML example ```yaml theme={null} sip: room_prefix: "sip-" allowed_addresses: - "192.168.1.0/24" - "10.0.0.1" hooks: - host: "example.com" url: "https://webhook.example.com/events" auth_id: "tenant-123" - host: "another.com" url: "https://webhook2.example.com/events" auth_id: "tenant-456" ``` ### Environment variables | Variable | Required | Description | | ----------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `SIP_ROOM_PREFIX` | Yes | Prefix every SIP-related LiveKit room must start with (alphanumeric, `-`, `_`). | | `SIP_ALLOWED_ADDRESSES` | No | Comma-separated IPv4 addresses/CIDRs. Whitespace is trimmed. | | `SIP_HOOKS_JSON` | No | JSON array of `{ "host": "...", "url": "https://...", "auth_id": "..." }` objects. HTTPS required; `auth_id` required when `AUTH_REQUIRED=true`. | ```bash theme={null} export SIP_ROOM_PREFIX="sip-" export SIP_ALLOWED_ADDRESSES="192.168.1.0/24,10.0.0.1" export SIP_HOOKS_JSON='[{"host":"example.com","url":"https://webhook.example.com/events","auth_id":"tenant-123"}]' ``` ### Precedence ``` Environment variables > YAML file > (feature disabled) ``` If a value is supplied via env vars it replaces the YAML counterpart entirely (lists are not merged). ## Validation rules * Cannot be empty * Only alphanumeric, `-`, `_` * Examples: `sip-`, `room_42` * List cannot be empty when SIP block exists * Each entry must resemble IPv4 or CIDR (`X.X.X.X/Y`) * IPv6 not supported yet * Hostnames must be unique (case-insensitive) * URLs must start with `https://` * Rejects insecure `http://` hooks * `auth_id` required when `AUTH_REQUIRED=true` Sayna validates the block at startup and fails fast with descriptive errors so you never run half-configured SIP resources. ## Auto-provisioning workflow When SIP config and LiveKit credentials are present, Sayna provisions everything automatically during startup. Creates `sayna-{room_prefix}-trunk` with your `allowed_addresses` list. Creates `sayna-{room_prefix}-dispatch` that routes SIP calls into LiveKit rooms matching the prefix (max 3 participants by default). Existing resources are reused; provisioning failures abort startup with clear logs so you can fix credentials or LiveKit connectivity issues. **Required credentials** * `LIVEKIT_API_KEY` * `LIVEKIT_API_SECRET` * Valid `sip` block or env vars **Observability** ```text theme={null} INFO SIP configuration detected, provisioning LiveKit SIP trunk and dispatch rules INFO Successfully provisioned SIP resources: trunk=sayna-sip--trunk, dispatch=sayna-sip--dispatch ``` Missing credentials simply log an info and skip provisioning; errors panic with the trunk/dispatch names for easier debugging. Verify resources via the LiveKit UI under **SIP → Inbound Trunks / Dispatch Rules**. ## Runtime behavior ### Room prefix matching Any LiveKit room whose name begins with `room_prefix` is treated as SIP. This heuristic drives routing logic, logging, and webhook forwarding. ### IP filtering `allowed_addresses` becomes the allowlist enforced by LiveKit. Use it to restrict inbound SIP traffic to trusted carriers or local networks. ### Webhook forwarding When LiveKit delivers webhooks, Sayna optionally forwards the **exact** JSON payload to downstream HTTPS hooks based on the SIP `To` header: 1. Inspect `participant.attributes["sip.h.to"]` (populated by LiveKit SIP). 2. Parse the host portion (e.g., `sip:calls@sip1.example.com` → `sip1.example.com`). 3. Match the host to entries in `hooks` (case-insensitive). 4. Post the payload to `hook.url` using the shared `ReqManager` so pooling/limits match the rest of the platform. 5. If no hook matches, log the omission but still respond `200 OK` to LiveKit. Forwarding runs asynchronously so LiveKit acknowledgements stay fast. With no hooks configured, the handler no-ops. ### Per-request configuration overrides When initiating outbound SIP calls via the `/sip/call` endpoint, you can override specific SIP settings on a per-request basis without changing the global configuration. This is useful for multi-provider scenarios or when different calls require different credentials. Per-request overrides take priority over global server configuration. If neither the request nor global config provides an `outbound_address`, the call will fail. See the [SIP call API reference](/api-reference/endpoint/sip-call) for full details on the `sip` configuration object and supported fields. ### Runtime hook management You can inspect and update the forwarding table without restarting the server: * `GET /sip/hooks` returns the cached list of `{ host, url, auth_id }` entries. * `POST /sip/hooks` replaces hooks with matching hosts (case-insensitive) and adds new ones, then persists the result. The `auth_id` field determines room ownership for inbound calls. Runtime additions reuse the global hook secret; per-hook secrets are not stored. Both endpoints respect `AUTH_REQUIRED=true` if you enforce auth globally. Always use unique hosts and HTTPS URLs or the request will be rejected. ## Reference configurations **Single carrier** ```yaml theme={null} sip: room_prefix: "sip-" allowed_addresses: - "203.0.113.0/24" hooks: - host: "sip-provider.example.com" url: "https://backend.myapp.com/sip/events" auth_id: "tenant-main" ``` **Multiple carriers** ```yaml theme={null} sip: room_prefix: "sip-" allowed_addresses: - "203.0.113.0/24" - "198.51.100.0/24" hooks: - host: "provider-a.example.com" url: "https://backend.myapp.com/sip/provider-a" auth_id: "tenant-a" - host: "provider-b.example.com" url: "https://backend.myapp.com/sip/provider-b" auth_id: "tenant-b" ``` **Local testing** ```yaml theme={null} sip: room_prefix: "test-sip-" allowed_addresses: - "127.0.0.1" - "192.168.1.0/24" hooks: - host: "localhost" url: "https://localhost:8443/webhooks" auth_id: "dev-tenant" ``` ## Accessing config in code ```rust theme={null} use sayna::config::ServerConfig; fn main() -> anyhow::Result<()> { let config = ServerConfig::from_env()?; if let Some(sip) = &config.sip { tracing::info!(prefix = %sip.room_prefix, count = sip.hooks.len(), "SIP enabled"); for hook in &sip.hooks { tracing::debug!( host = %hook.host, url = %hook.url, auth_id = %hook.auth_id, "Configured SIP hook" ); } } else { tracing::info!("SIP disabled"); } Ok(()) } ``` ## Troubleshooting | Error | Cause | Fix | | --------------------------------------------------------------- | ----------------------------------------------------------- | --------------------------------------------- | | `SIP room_prefix is required when SIP configuration is present` | Allowed addresses or hooks were specified without a prefix. | Set `SIP_ROOM_PREFIX` or the YAML equivalent. | | `SIP hook URL must be HTTPS` | Hook used `http://`. | Update to `https://` for every entry. | | `Duplicate SIP hook host` | Same host appears twice (case-insensitive). | Ensure each host is unique. | | `SIP allowed_address '...' does not look valid` | Invalid IPv4/CIDR string. | Replace with real IPv4 or `x.x.x.x/y` CIDR. | ## Related docs * [SIP call API](/api-reference/endpoint/sip-call) – initiate outbound SIP calls with optional per-request configuration overrides. * [Configure Twilio SIP](/guides/sip-twilio) – walk through Twilio Elastic SIP Trunking setup using Sayna's SIP endpoint. * [Authentication](/guides/authentication) – protect webhook receivers and REST APIs. * [Deployment guide](/guides/deployment) – configure LiveKit credentials alongside SIP env vars. ## Future enhancements Planned improvements include IPv6 allowlists, configurable webhook retry policies, wildcard host matching, payload signing, and per-hook credentials. Track release notes for updates. # SIP routing Source: https://docs.sayna.ai/guides/sip-routing How Sayna preserves SIP destinations and fans out LiveKit webhooks to the right tenant. Sayna keeps multi-tenant SIP traffic cleanly separated by preserving the caller’s original destination through the entire path: carrier ➝ proxy ➝ LiveKit ➝ Sayna ➝ customer webhook. This guide distills the architecture and the routing rules that keep each tenant’s events isolated. Use this when you have one LiveKit SIP deployment serving many customers and need deterministic webhook delivery per domain. ## Architecture ```mermaid theme={null} flowchart TB subgraph PSTN A["Carrier
INVITE to tenant domain"] end subgraph Edge["SIP edge"] B["Kamailio proxy
Extracts original host
Adds X-To-IP"] C["LiveKit SIP
Creates room + participant
Exposes sip.h.* attributes"] end subgraph Sayna D["Webhook receiver
Validates LiveKit signature"] E["Domain resolver
sip.h.x-to-ip → sip.h.to fallback"] F["Tenant router
Signs + forwards to mapped webhook"] end subgraph Tenants G["Customer A webhook"] H["Customer B webhook"] I["Customer C webhook"] end A --> B B --> C C -->|participant_joined webhook| D D --> E E --> F F --> G F --> H F --> I ``` ## End-to-end flow The PSTN carrier sends an INVITE to the customer-facing SIP domain (for example, `customer-a.com`). Kamailio terminates the INVITE so it can inspect headers before forwarding. Kamailio extracts the host from the Request-URI or `To` header, writes it into `X-To-IP`, and then forwards the call to LiveKit SIP. This keeps the tenant hint intact even if the `To` header is rewritten. LiveKit creates the SIP participant and exposes every SIP header as a participant attribute (`sip.h.`), making `sip.h.x-to-ip` available for routing. Standard attributes like `sip.phoneNumber`, `sip.trunkPhoneNumber`, and `sip.callID` travel alongside. When LiveKit emits `participant_joined`, Sayna validates the webhook signature, checks that SIP attributes exist, and extracts the routing domain with a strict priority order. Sayna looks up the domain in the SIP hook table, signs the payload with HMAC-SHA256, and forwards asynchronously to the configured HTTPS endpoint for that tenant. Missing or malformed domains are logged but never block LiveKit acknowledgements. ## Component responsibilities | Component | Role | Notes | | ---------------------- | -------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | | PSTN carrier | Delivers the INVITE to your SIP edge based on DID ownership. | Must target the tenant-facing domain so Kamailio can capture it. | | Kamailio SIP proxy | Adds `X-To-IP` with the original destination host before sending to LiveKit. | Avoids losing the tenant hint when `To` is rewritten; acts as the authoritative source for routing. | | LiveKit SIP | Bridges the call into a room and surfaces SIP headers as participant attributes. | Attributes are prefixed with `sip.h.`; the room name typically uses the SIP room prefix plus the called number. | | Sayna webhook receiver | Validates LiveKit signatures and extracts routing attributes. | Skips non-SIP webhooks and continues even when routing data is missing, to keep LiveKit healthy. | | Tenant webhooks | Consume signed events for their own calls. | Each host maps to one HTTPS URL; downstream systems verify HMAC headers from Sayna. | ## Domain extraction rules * Priority: `sip.h.x-to-ip` takes precedence; `sip.h.to` is the fallback when the custom header is absent. * Parsing: hostnames are pulled from SIP URIs, display-name formats, or plain host strings; ports and parameters are discarded. * Normalization: domains are lowercased for case-insensitive matching against the hook table. | SIP header value | Parsed domain | | ----------------------------------------- | -------------------- | | `sip:user@example.com` | `example.com` | | `"Display Name" ` | `example.com` | | `sip:user@example.com;user=phone;tag=xyz` | `example.com` | | `sips:user@secure.example.com` | `secure.example.com` | | `example.com:5060` | `example.com` | | `sip-1.example.com` | `sip-1.example.com` | If neither `sip.h.x-to-ip` nor `sip.h.to` can be parsed into a domain, Sayna logs the condition and skips forwarding. ## Webhook fan-out behavior * **Signature verification**: LiveKit webhooks must pass JWT validation before routing begins. * **SIP-only enforcement**: Events without SIP attributes are acknowledged but never forwarded. * **Hook lookup**: Domains are matched against the configured hook list (case-insensitive). Missing entries produce warnings rather than errors. * **Payload signing**: Forwarded requests include `X-Sayna-Signature`, `X-Sayna-Timestamp`, `X-Sayna-Event-Id`, and `X-Sayna-Signature-Version` for downstream verification. * **Asynchronous delivery**: Forwarding runs off the main webhook handler to keep LiveKit responses fast; retries depend on downstream HTTP results and your operational policies. ### Payload shape (conceptual) | Field | Meaning | | ------------------------------------------------------------- | ----------------------------------------------------------------------------------- | | `participant.name`, `participant.identity`, `participant.sid` | Identifiers for the SIP caller inside the LiveKit room. | | `room.name`, `room.sid` | The LiveKit room created for the call, typically prefixed with the SIP room prefix. | | `from_phone_number` | The caller’s number from the SIP attributes. | | `to_phone_number` | The called DID that triggered this room. | | `room_prefix` | Configured SIP room prefix to distinguish SIP traffic. | | `sip_host` | The domain used to choose the webhook destination. | ## Hook model and lifecycle * **Mapping**: Each hook entry pairs a host (tenant domain) with an HTTPS webhook URL and an `auth_id`; hostnames must be unique. * **Room ownership**: The `auth_id` field determines who owns rooms created from inbound SIP calls. When a call arrives, Sayna sets `room.metadata.auth_id` to the hook's `auth_id` value. * **Sources of truth**: Hooks load from configuration at startup and can be updated at runtime through the SIP hook APIs; runtime changes persist across restarts. * **Security**: HTTPS is required, and all forwarded calls are HMAC-signed so tenants can authenticate Sayna. * **Operations**: Adding, replacing, or removing a host takes effect immediately for new events; existing in-flight calls keep their resolved destination. When `AUTH_REQUIRED=true`, the `auth_id` field is required for each SIP hook entry. This ensures that inbound SIP calls are properly associated with a tenant for room access control. ## Reliability checklist * Confirm Kamailio always stamps `X-To-IP` so the strongest routing signal is present. * Monitor webhook forwarding logs for “no webhook configured for domain” and align hook entries with the domains your carriers use. * Validate `sip.h.to` parsing in LiveKit traces when troubleshooting unexpected skips. * Keep hook secrets long and rotate them with tenants periodically. * Track downstream failures (timeouts, TLS issues, DNS resolution) since Sayna will log but not retry indefinitely without operator action. # Configure Twilio SIP Source: https://docs.sayna.ai/guides/sip-twilio Point Twilio Elastic SIP Trunking at Sayna’s SIP endpoint and let Sayna handle the LiveKit plumbing. Sayna auto-provisions the LiveKit SIP trunk + dispatch rule as soon as you populate the [`sip` configuration](/guides/sip) and provide `LIVEKIT_API_KEY` / `LIVEKIT_API_SECRET`. All you need to do on the carrier side is tell Twilio where to send calls. > **TL;DR** – Create/choose a Twilio Elastic SIP trunk, add Sayna’s SIP domain/IP to the **Origination** list as a SIP URI (e.g., `sip:sip.sayna.ai;transport=tcp`), and make sure Twilio’s source IP ranges are present in `SIP_ALLOWED_ADDRESSES`. ## Prerequisites 1. `sip` block configured in Sayna (`room_prefix`, `allowed_addresses`, optional `hooks`). 2. Public DNS record or static IP that routes to your Sayna deployment (Load balancer, ingress, etc.). 3. LiveKit credentials so Sayna can create the trunk + dispatch rule automatically. 4. Twilio account with Elastic SIP Trunking enabled. Sayna creates the LiveKit resources (names `sayna-{prefix}-trunk` / `sayna-{prefix}-dispatch`) so you **do not** need to follow LiveKit’s manual steps from their quickstarts. Focus on the Twilio console configuration only. ## Step 1 — Expose Sayna’s SIP endpoint * Pick a hostname such as `sip.yourcompany.com` that resolves to the Sayna service running with SIP enabled. * Ensure TCP 5060/5061 reaches Sayna (or whatever port your reverse proxy exposes for SIP traffic). * Add Twilio’s regional egress IP ranges to `SIP_ALLOWED_ADDRESSES` so Sayna accepts their traffic. Twilio lists these ranges in the [Elastic SIP Trunking IP access control documentation](https://www.twilio.com/docs/sip-trunking/ip-addresses) — copy the ranges for every region you plan to use. Example env vars: ```bash theme={null} export SIP_ROOM_PREFIX="sip-" export SIP_ALLOWED_ADDRESSES="54.172.60.0/23,34.203.250.0/23,52.40.51.128/25" # Twilio us-east-1 + us-west-2 export SIP_HOOKS_JSON='[{"host":"sip.yourcompany.com","url":"https://backend.yourcompany.com/sip/events"}]' ``` Once Sayna boots, it provisions the LiveKit trunk/dispatch and you’ll see log lines similar to: ```text theme={null} INFO Successfully provisioned SIP resources: trunk=sayna-sip--trunk, dispatch=sayna-sip--dispatch ``` ## Step 2 — Create or select a Twilio trunk 1. In the Twilio Console, navigate to **Elastic SIP Trunking → Trunks**. 2. Create a new trunk or open an existing one dedicated to Sayna. 3. Give it a meaningful name (e.g., `SaynaBridge`). You do not need to configure **Termination** for this integration unless you want Sayna to place outbound PSTN calls via Twilio. We only care about **Origination** (Twilio → Sayna). ## Step 3 — Configure origination URI Twilio needs to know where to send inbound SIP INVITE requests. Use the domain/IP where Sayna listens for SIP traffic. 1. Inside the trunk, go to the **Origination** tab. 2. Click **Add new Origination URI**. 3. Set **SIP URI** to the Sayna address with TCP enforced: ```text theme={null} sip:sip.yourcompany.com;transport=tcp ``` 4. (Optional) Specify a **Friendly Name** like “Sayna Primary”. 5. Leave the weight/priority defaults unless you have multiple Sayna regions. 6. Save the trunk. Twilio supports TLS/SRTP as well, but Sayna currently expects TCP. Keep the `;transport=tcp` suffix in the URI to avoid UDP-only failures. Behind the scenes Twilio now dials `sip.yourcompany.com` whenever the trunk’s phone numbers receive a call. Sayna detects the `room_prefix`, routes the call into the auto-provisioned LiveKit room, and forwards events/webhooks per your SIP configuration. ## Step 4 — Map numbers to the trunk 1. Still in the Twilio Console, open **Phone Numbers → Manage → Active numbers**. 2. Assign the desired DID(s) to the trunk you configured. 3. Test by dialing the number and watching Sayna logs—the connection should hit the SIP trunk and trigger your WebSocket workflow. ## Operational checklist * **Allowed addresses** – keep Twilio IP ranges current; Twilio occasionally adds regions. * **Health checks** – monitor Sayna logs for `Failed to provision SIP resources` to catch LiveKit credential issues early. * **Recording + hooks** – configure `livekit.enable_recording` and `SIP_HOOKS_JSON` in Sayna if you want downstream webhooks when Twilio callers join/leave. * **Twilio failover** – add a backup Origination URI (secondary Sayna region) with lower priority if you run multi-region fleets. ## Troubleshooting | Symptom | Likely cause | Fix | | ------------------------------------------------- | ---------------------------------------------- | ---------------------------------------------------------------------------------------------------- | | Twilio calls immediately fail | Origination URI unreachable or wrong transport | Verify DNS resolves to Sayna, firewall allows TCP 5060/5061, and URI uses `;transport=tcp`. | | Twilio 403/603 responses | Sayna rejected IP | Add the relevant Twilio IP range/CIDR to `SIP_ALLOWED_ADDRESSES`. | | Sayna logs “SIP room\_prefix is required” | SIP env vars incomplete | Set `SIP_ROOM_PREFIX` (and other SIP vars) before starting Sayna. | | Calls reach Sayna but never hit LiveKit | LiveKit credentials missing or invalid | Ensure `LIVEKIT_API_KEY`/`LIVEKIT_API_SECRET` are configured so auto-provisioning can join the room. | | | | | | LiveKit room created but no downstream hooks fire | `SIP_HOOKS_JSON` empty or host mismatch | Populate hooks with the domains you expect in `sip.h.to` headers. | ## Related docs * [SIP configuration](/guides/sip) – field-by-field breakdown of Sayna’s SIP options (room prefix, hooks, auto-provisioning). * [Twilio guide](https://docs.livekit.io/sip/quickstarts/configuring-twilio-trunk/) – reference article that inspired this flow (follow only the Twilio console steps; Sayna handles the LiveKit pieces). # WebSocket API Source: https://docs.sayna.ai/guides/websocket Stream audio, queue speech, and coordinate LiveKit rooms through a single connection. Sayna’s `/ws` endpoint is the control plane for every real-time experience. A single socket handles streaming audio, transcription events, TTS playback, and LiveKit data. This page distills the full protocol from the engineering brief (`tmp/docs/websocket.mdoc`) into actionable reference material. ## End-to-end flow ```text theme={null} Client ──► Connect /ws └─► send {"type":"config", ...} Sayna ──► validate + spin up providers + optional LiveKit join Sayna ──► send {"type":"ready", ...} Client ◄── start streaming audio / send commands Client & Sayna ── keep exchanging JSON control frames + binary audio Either side closes socket → Sayna tears down providers + LiveKit room ``` Open a WS connection (`ws://host:3001/ws` or `wss://`). Ping/pong is automatic; idle sockets close after \~10 s of silence. The very first client message must be `type: "config"`. Sayna injects credentials, boots STT/TTS providers, provisions LiveKit (if configured), warms caches, and responds with `ready` once every subsystem is up (30 s timeout). Stream binary PCM/Opus frames, queue `speak` jobs, drive the loading indicator with `loading_start` / `loading_stop`, forward LiveKit data via `send_message`, and react to `stt_result`, `message`, `participant_disconnected`, and binary TTS audio frames. On close (client, timeout, or LiveKit departure) Sayna halts providers, stops recordings, leaves/deletes the room, flushes caches, and releases file handles. ## Message taxonomy | Direction | Type | Purpose | | --------------- | -------------------------- | ----------------------------------------------------------------------------------------------- | | Client → Server | `config` | Declare STT/TTS/livekit setup; must come first. | | | Binary audio | Raw PCM/Opus chunks that match `stt_config`. | | | `speak` | Queue TTS synthesis (optionally override defaults per call). | | | `clear` | Flush TTS buffers (WebSocket + LiveKit) unless playback is locked. | | | `loading_start` | Begin looping the configured `loading_audio` clip on a dedicated `loading-audio` LiveKit track. | | | `loading_stop` | Stop the loading loop with a short fade-out. Idempotent and silent server-side. | | | `send_message` | Publish JSON payloads over the LiveKit data channel. | | | `sip_transfer` | Transfer the current SIP call to another phone number. | | | `update_config` | Dynamically adjust VAD and turn detection parameters. | | Server → Client | `ready` | Providers + LiveKit are initialized; safe to stream. | | | `stt_result` | Interim/final transcripts with `is_final` / `is_speech_final`. | | | Binary audio | TTS playback chunks in the negotiated format. | | | `message` | Informational notices (LiveKit state, provider hints, etc.). | | | `tts_playback_complete` | Signals a `speak` request finished emitting audio. | | | `participant_connected` | LiveKit peer joined the room. | | | `participant_disconnected` | LiveKit peer left → Sayna closes the socket after 100 ms. | | | `track_subscribed` | Sayna subscribed to a participant’s media track. | | | `vad_event` | VAD activity change: speech start, silence, resume, or turn end. | | | `error` | Validation/provider issues; connection usually stays open so you can retry. | | | `sip_transfer_error` | SIP transfer operation failed. | ## Configuration message ```json theme={null} { "type": "config", "stream_id": "support-call-123", "audio": true, "stt_config": { "provider": "deepgram", "language": "en-US", "sample_rate": 16000, "channels": 1, "punctuation": true, "encoding": "linear16", "model": "nova-3", "auth": { "api_key": "your-deepgram-key" } }, "tts_config": { "provider": "elevenlabs", "model": "eleven_flash_v2_5", "voice_id": "voice_id_here", "speaking_rate": 1.0, "audio_format": "linear16", "sample_rate": 24000, "auth": { "api_key": "your-elevenlabs-key" } }, "livekit": { "room_name": "conversation-room-123", "enable_recording": true, "sayna_participant_identity": "sayna-ai", "sayna_participant_name": "Sayna AI", "listen_participants": [] }, "loading_audio": { "data": "UklGRiQAAABXQVZFZm10IBAAAAABAAEA...", "format": "wav", "volume": 0.3 } } ``` * `audio=false` skips STT/TTS initialization but still allows LiveKit control + data channel relays. * `stream_id` is optional; provide one to control recording paths and correlate sessions, or let Sayna generate a UUID v4 and return it in the `ready` message. * `stt_config.sample_rate/channels/encoding` must exactly match the binary frames you send—Sayna will not resample. * `tts_config` values become session defaults; individual `speak` messages can override most fields or add `id` for correlation. * `stt_config.auth` and `tts_config.auth` are optional objects that supply provider credentials for this session only. When provided, they fully replace server-configured credentials (no partial merge). Omit or send `{}` to use server defaults. See [Provider auth overrides](#provider-auth-overrides) below for supported shapes per provider. * The `livekit` block is optional but required for `send_message` and mirrored playback/recording. * `loading_audio` is optional and additive; it is only processed when `audio=true` and the `livekit` block is present, and a decode failure is **non-fatal** (the session continues without loading capability). See the dedicated [Loading indicator](#loading-indicator) section below. ## Streaming audio best practices * Chunk size: \~100–200 ms of audio per binary frame (e.g., 3 200 bytes for 16 kHz mono linear16). * Maintain consistent cadence; bursty uploads increase STT latency. * Enable `punctuation` + `turn-detect` (default features) when you need `is_speech_final` cues to know when a speaker stopped. * If the client detects a barge-in (human interrupts AI), send `{"type":"clear"}` before queueing new `speak` text. ## Client commands in detail ### `speak` ```json theme={null} { "type": "speak", "text": "Hello! How can I help you today?", "flush": true, "allow_interruption": true, "tts_config": {"voice_id": "aura-luna-en"}, "id": "greeting-1" } ``` * `flush=true` clears queued audio before speaking; set `false` to build playlists. * `allow_interruption=false` protects critical prompts even if the client sends `clear`. * `tts_config` may override any session default, including provider credentials via the `auth` field. * Finish signal arrives via `tts_playback_complete` with the same `id`. ### `loading_start` ```json theme={null} { "type": "loading_start" } ``` Begins the loading-indicator audio loop on the dedicated `"loading-audio"` LiveKit track. Fire-and-forget; idempotent if the loop is already running. Requires `audio=true`, an active LiveKit room, and a `loading_audio` clip supplied in the initial `config` message. Failures (no `config` yet, audio disabled, no LiveKit room, missing or undecodable `loading_audio`, track publish failure) surface as `error` messages on the existing error channel. ### `loading_stop` ```json theme={null} { "type": "loading_stop" } ``` Stops the loading loop with a short fade-out (\~30 ms). Fire-and-forget, idempotent, and **always silent** server-side — stopping when nothing is playing or when no LiveKit room exists is a harmless no-op, never an error. Because `speak` does not stop the loop, **applications must send `loading_stop` before (or together with) `speak`** in the normal "thinking finished, now answer" flow. Otherwise the loading sound continues playing under the spoken answer. ### `send_message` ```json theme={null} { "type": "send_message", "message": "{\"action\":\"typing\"}", "role": "assistant", "topic": "status", "debug": {"source": "sayna-ai", "version": "1.0"} } ``` Used when Sayna should notify LiveKit participants via data channels (chat bubbles, control events). Requires a `livekit` block in the configuration message. ## Server events in detail ### `ready` Echoes the session `stream_id` (provided or auto-generated), LiveKit metadata (room name, URLs, participant identity), and signals that STT/TTS providers finished booting. Use that `stream_id` later with `GET /recording/{stream_id}` when recording is enabled. Other participants still need to call `POST /livekit/token` to join the room. ### `stt_result` ```json theme={null} { "type": "stt_result", "transcript": "Hello, how are you today?", "is_final": true, "is_speech_final": true, "confidence": 0.94 } ``` * Interim updates set `is_final=false` and keep streaming as long as audio flows. * The final chunk for an utterance flips `is_final=true`. * `is_speech_final=true` indicates the turn detector heard silence—ideal for triggering a response. ### `message` and `participant_disconnected` Utility events for LiveKit mirroring: ```json theme={null} {"type":"message","label":"livekit.joined","details":{"identity":"user-123"}} {"type":"participant_disconnected","participant":{"identity":"user-123","name":"Alex"}} ``` When a `participant_disconnected` event arrives, expect Sayna to close the WebSocket 100 ms later so the LiveKit room is torn down cleanly. ### Binary TTS payloads Binary frames deliver synthesized audio in the format you declared (e.g., 24 kHz linear16). Handle them alongside JSON control frames: ```javascript theme={null} socket.onmessage = (event) => { if (event.data instanceof Blob) playAudioChunk(event.data); else handleControl(JSON.parse(event.data)); }; ``` ## Provider auth overrides Both `stt_config` and `tts_config` accept an optional `auth` object that lets clients supply provider credentials per WebSocket session or per `POST /speak` request. This is useful for multi-tenant deployments, customer-managed provider keys, and per-request credential routing. ### Fallback behavior * If `auth` is omitted, the server uses its configured provider credentials. * If `auth` is sent as an empty object `{}`, the server also falls back to its configured credentials. ### No partial merge If `auth` is provided, it must be complete for that provider. The server does not merge a partial `auth` object with server-side credentials. For example, sending Azure `auth` with only `api_key` and no `region` is invalid. ### Supported auth shapes | Provider | Shape | Required fields | | ------------ | --------------------------------------- | --------------------------------------------------------------- | | Deepgram | `{ "api_key": "..." }` | `api_key` | | ElevenLabs | `{ "api_key": "..." }` | `api_key` | | Cartesia | `{ "api_key": "..." }` | `api_key` | | Google Cloud | `{ "credentials": "..." }` | `credentials` (file path string or JSON service account object) | | Azure Speech | `{ "api_key": "...", "region": "..." }` | `api_key`, `region` | ### Validation Clients should expect session or request initialization to fail if: * Required auth fields for the selected provider are missing. * Auth field types are invalid. * Unsupported auth keys are sent for that provider. * The provider name is unsupported. The `provider` value in `stt_config.provider` or `tts_config.provider` determines how the `auth` object is interpreted — the `auth` object itself does not include a provider discriminator. ## Loading indicator The loading indicator is a short audio clip looped into the LiveKit room while your application is busy ("thinking") and cannot yet answer. It is the audio equivalent of a spinner. The clip plays on its own dedicated LiveKit audio track named `"loading-audio"`, separate from the `"tts-audio"` speech track, so it never interferes with text-to-speech output. ### `loading_audio` configuration Include a `loading_audio` object in the initial `config` message. The server decodes and validates the clip once at config time and holds the validated buffer for the session. | Field | Type | Required | Description | | ------------- | ---------------- | ----------- | --------------------------------------------------------------------------------------------------------- | | `data` | string | Yes | Base64-encoded audio bytes — a complete WAV file or raw 16-bit little-endian PCM. | | `format` | `"wav" \| "pcm"` | No | Container hint. If omitted, the server auto-detects from the `RIFF`/`WAVE` signature. | | `sample_rate` | integer | Conditional | Sample rate in Hz (8000–48000). **Required for raw PCM**; ignored for WAV (the header is authoritative). | | `channels` | integer | No | `1` (mono) or `2` (stereo). Defaults to `1`. Ignored for WAV. | | `volume` | number | No | Playback volume `0.0`–`1.0`. Default `1.0`; out-of-range values are clamped; applied once at config time. | **Audio requirements** * Only 16-bit PCM is supported (16-bit integer WAV, or raw 16-bit little-endian PCM). Other bit depths are rejected. * Decoded duration: \~250 ms to \~10 s, **1–4 s recommended**. * Decoded size is capped at \~1.9 MB. * Author the clip so its start and end amplitudes match — otherwise the loop seam will click. * Author the clip quiet enough to sit *under* speech rather than compete with it. **Behavioral rules** * `loading_audio` is processed only when `audio=true` **and** a `livekit` block is present in the same `config` message. Supplied without those, the server emits an `error` and continues the session without loading capability. * Decode or validation failures are **non-fatal** — the session continues, STT/TTS are unaffected, and only the loading feature is unavailable. A later `loading_start` re-reports the original decode error so the failure is never silent. ### Controlling the loop The loop is controlled **exclusively** by the [`loading_start`](#loading_start) and [`loading_stop`](#loading_stop) commands. `speak` and `clear` do *not* affect it. Server-side, the loop also stops automatically on session teardown / disconnect. The server does **not** stop the loop when VAD detects user speech. If you want the loading audio to end on barge-in, send `loading_stop` from your `vad_event` or `stt_result` handler. ### Typical turn ```text theme={null} client → stt_result (final, is_speech_final=true) client → {"type": "loading_start"} # background work begins …application calls its LLM/tools… client → {"type": "loading_stop"} # background work ends — stop BEFORE speak client → {"type": "speak", "text": "Here is what I found…"} ``` ## LiveKit interplay * Sayna manages the agent-side participant automatically; humans still fetch tokens via `POST /livekit/token`. * `listen_participants` limits which identities can feed audio back into Sayna. * Recordings respect your LiveKit/S3 configuration when `enable_recording=true`; files are stored at `{server_prefix}/{stream_id}/audio.ogg` using the `stream_id` from your config or the ready message. * `send_message` and `clear` affect both the WebSocket client and LiveKit room so playback remains in sync. ## Troubleshooting | Symptom | Likely cause | Fix | | ------------------------------------------------------------------ | ---------------------------------------------- | --------------------------------------------------------------------- | | `error: STT and TTS configurations required when audio is enabled` | `audio=true` but one of the configs missing. | Provide both `stt_config` and `tts_config`, or set `audio=false`. | | WebSocket closes right after `participant_disconnected` | LiveKit peer left. | Reconnect / reconfigure to start a new session. | | Garbled transcripts | Audio frame format doesn’t match `stt_config`. | Ensure sample rate, channels, and encoding align with captured audio. | | LiveKit data messages rejected | `send_message` used without `livekit` section. | Include LiveKit config in the initial `config` payload. | | Loading audio plays under the spoken answer | `speak` was sent before `loading_stop`. | Send `loading_stop` immediately before (or together with) `speak`. | Need more detail on SIP routing or carrier setup? Pair this guide with the [SIP configuration](/guides/sip) and [Twilio SIP setup](/guides/sip-twilio) references. # Sayna overview Source: https://docs.sayna.ai/index Real-time speech infrastructure powered by Rust, LiveKit, and pluggable providers. Sayna combines low-latency WebSockets, one-shot REST helpers, and LiveKit mirroring so you can ship voice-first experiences quickly. These docs explain the moving parts, how to deploy securely, and where to find the OpenAPI reference. Sayna voice flow animation Follow the quickstart to configure providers, boot the container, and hit the first endpoints. ## Build with confidence Dive into the VoiceManager, provider layer, caching, and feature flags. Learn what each endpoint accepts and how caching works. Review the config, command, and event schemas that drive real-time voice. Point Twilio trunks at Sayna’s SIP endpoint and keep LiveKit rooms in sync. ## Operate safely Ship Sayna in Docker, Compose, or Kubernetes with the right env vars. Choose between shared secrets and delegated JWT validation. Adopt caching, observability, and release best practices. Explore the OpenAPI spec plus interactive endpoint playgrounds. # Quickstart Source: https://docs.sayna.ai/quickstart Bring up Sayna locally, wire credentials, and hit your first endpoints. This walkthrough assumes you have Docker installed plus API keys for at least one TTS/STT provider (Deepgram or ElevenLabs) and optional LiveKit credentials. Prefer a managed LiveKit instance? Point `LIVEKIT_URL` at the internal signaling address and `LIVEKIT_PUBLIC_URL` at the client-facing domain. ```bash theme={null} git clone https://github.com/your-org/sayna.git cd sayna cp .env.example .env ``` You can keep using `.env`, but for local development it’s often clearer to generate a config file and pass it to Sayna: ```yaml theme={null} server: host: "0.0.0.0" # ENV: HOST port: 3001 # ENV: PORT livekit: url: "ws://localhost:7880" # ENV: LIVEKIT_URL public_url: "http://localhost:7880" # ENV: LIVEKIT_PUBLIC_URL api_key: "devkey" # ENV: LIVEKIT_API_KEY api_secret: "secret" # ENV: LIVEKIT_API_SECRET providers: deepgram_api_key: "your-deepgram-api-key" # ENV: DEEPGRAM_API_KEY elevenlabs_api_key: "your-elevenlabs-api-key" # ENV: ELEVENLABS_API_KEY ``` ```dotenv theme={null} HOST=0.0.0.0 PORT=3001 LIVEKIT_URL=ws://localhost:7880 LIVEKIT_PUBLIC_URL=http://localhost:7880 LIVEKIT_API_KEY=devkey LIVEKIT_API_SECRET=secret DEEPGRAM_API_KEY=your-deepgram-api-key ELEVENLABS_API_KEY=your-elevenlabs-api-key ``` LiveKit needs Redis for state. Run both with Docker Compose: ```yaml theme={null} services: redis: restart: always image: redis:alpine livekit: image: livekit/livekit-server:v1.9.1 command: --dev --bind=0.0.0.0 restart: always environment: LIVEKIT_CONFIG: | port: 7880 log_level: info rtc: tcp_port: 7881 port_range_start: 50000 port_range_end: 60000 redis: address: redis:6379 ports: - "7880:7880" - "7881:7881" ``` Keep this stack running so Sayna can reach LiveKit on the internal network (`ws://localhost:7880` or `ws://livekit:7880` if you use the Docker Compose file). If you created `config.yaml`, run: ```bash theme={null} cargo run -- -c config.yaml ``` or simply `cargo run` when environment variables are already loaded (e.g., via `.env`). Prefer Docker? Add a Sayna service to the same Compose file so it shares the network with LiveKit: ```yaml theme={null} services: sayna: build: . depends_on: - livekit environment: HOST: 0.0.0.0 PORT: 3001 LIVEKIT_URL: ws://livekit:7880 LIVEKIT_PUBLIC_URL: http://localhost:7880 LIVEKIT_API_KEY: devkey LIVEKIT_API_SECRET: secret DEEPGRAM_API_KEY: your-deepgram-api-key ELEVENLABS_API_KEY: your-elevenlabs-api-key ports: - "3001:3001" ``` Whether you use config files or env vars, make sure the Sayna container can resolve the LiveKit hostname (`livekit`) and expose port `3001` to your host machine. ```bash theme={null} curl http://localhost:3001/ curl http://localhost:3001/voices ``` Then connect a WebSocket client, send a `config` message, and queue a `speak` payload to hear a synthesized clip. Use `/livekit/token` to mint attendee tokens if you mirror audio into LiveKit. ## Next steps Understand the moving parts before you customize providers or pipelines. Learn what `/voices`, `/speak`, and `/livekit/token` expect. Explore the message schemas for low-latency experiences. Pick between API secrets and delegated JWT validation. # JavaScript SDK Source: https://docs.sayna.ai/sdks/js Use Sayna from any browser with a lightweight LiveKit helper. `@sayna-ai/js-sdk` is the browser-oriented companion to Sayna. It follows the official README and focuses on product builders who need to drop token fetching, microphone publishing, and remote audio playback into a front-end app without touching low-level WebRTC primitives. ## What it solves * **Token orchestration** – Fetch `/livekit/token` responses from your backend via a simple `tokenUrl`, or provide a custom `tokenFetchHandler` if you already control auth. * **Room lifecycle** – `connect()`, `publishMicrophone()`, and `disconnect()` manage the entire LiveKit flow and keep track of connection state for you. * **Remote playback** – The SDK can create and manage an `