# Call Center API Source: https://docs.lokutor.com/api-reference/call-center Phone numbers and calls under /callcenter: search, buy, assign and release numbers, dial one number or a list, hang up, and follow a live call with call-monitor (JSON or Server-Sent Events). Everything here lives under `/callcenter/*` on `https://api.lokutor.com`. The routes exist only on a server with telephony configured; where it is not, they are not registered at all and answer `404`. `api.lokutor.com` has telephony configured. For a step-by-step setup, see the [Phone agent quickstart](/guides/phone-agent-quickstart). **Authentication:** every endpoint takes an API key or `wst_` ticket as `Authorization: Bearer`, `X-API-Key` or `?api_key=` ([Authentication](/authentication)). The key must belong to an account (`401` otherwise). **Billing:** calls and numbers are paid from the account's prepaid balance ([Pricing and billing](/pricing#phone-calls)). Buying a number and placing calls need a first top-up: before it, those endpoints answer `402` with `{"code": "billing.topup_required", "error": "…"}`. With less than \$0.25 of balance they answer `402` `billing.insufficient_balance`, and while a payment is disputed, `billing.account_disputed`. **Account scope:** every endpoint acts only on the account that owns the key. The agents and numbers you list are your own. Assign, release, dial and bulk-dial work only with numbers you own and agents you own. A number or agent that belongs to another account answers `404` (`403` for a `from` number you don't own), whether or not it exists. The API needs a key that belongs to an account (`401` otherwise). *** ## `GET /callcenter/status` — Provisioning Status Whether calling is enabled, and through which carrier. ### Response ```json theme={null} { "enabled": true, "provider": "telnyx" } ``` *** ## `GET /callcenter/agents` — List Agents Returns every agent on the account, for populating a "route to agent" picker. ### Response ```json theme={null} { "agents": [ { "id": "34da7ae3-0d46-4827-8739-ca6a25dc756c", "name": "Front Desk", "voice": "F2", "language": "es" } ] } ``` *** ## `GET /callcenter/numbers/search` — Search Available Numbers Search the inventory of purchasable numbers, before committing to buy one. Only **local** numbers are offered, in the US, Spain, the UK, Germany, France, Italy and Portugal; any other `country_code` returns `400`. Outside the US, buying a number is refused with `number.documents_required` (HTTP 422, nothing charged) when the country's regulator requires the account holder's documents before activation, which Lokutor cannot collect yet. `monthly_cost` and `upfront_cost` in the results are the carrier's own figures, not what you pay: every Lokutor number is **\$5 a month** from your balance (`phone.number_per_month` in the [rate card](/api-reference/rate-card)). ### Query Parameters | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `country_code` | `string` | `"US"` | `US`, `ES`, `UK`, `DE`, `FR`, `IT` or `PT` | | `region_code` | `string` | — | Region or state, e.g. `CT` | | `locality` | `string` | — | City, e.g. `Madrid` | | `page` | `integer` | `1` | Results come 15 per page | ### Response ```json theme={null} { "numbers": [ { "phone_number": "+14755750358", "monthly_cost": "1.00000", "upfront_cost": "1.00000", "currency": "USD", "region": "CT", "locality": "RIDGEFIELD" } ], "page": 1, "total": 42 } ``` ### cURL ```bash theme={null} curl -s "https://api.lokutor.com/callcenter/numbers/search?country_code=US®ion_code=CT" \ -H "Authorization: Bearer $LOKUTOR_API_KEY" ``` *** ## `GET /callcenter/numbers` — List Owned Numbers Returns every number on the account, merged with its agent binding (if any). ### Response ```json theme={null} { "numbers": [ { "id": "1234567890", "phone_number": "+14755750358", "status": "active", "connection_id": "2972204047848703963", "agent_id": "34da7ae3-..." } ], "total": 1 } ``` `status` is `active` (the number can be used) or `activating`: the number is yours and paid for, but the carrier is still doing its regulatory review of the holder, which numbers in some countries need. An `activating` number cannot send or receive calls yet; it turns `active` by itself, with nothing to do or pay. `status_note` explains it in words and `telnyx_status` is the carrier's own value. *** ## `POST /callcenter/numbers` — Buy a Number Purchases a number **you have already found via search** — `phone_number` must be an exact result from [`/callcenter/numbers/search`](#get-/callcenter/numbers/search-—-search-available-numbers), not an arbitrary string. There's no "buy a random number for this country" shortcut; searching first is required. > [!WARNING] > > This rents the number for **\$5 a month from your balance**: the first month is charged when you buy it, then once a month. There's no confirmation step at the API level; the caller is the confirmation step. Buying a number needs a first top-up (`402``billing.topup_required` before it) and at least the first month in the balance (`402``billing.insufficient_balance`). A number whose own carrier price exceeds what a Lokutor number includes is refused with `400` before anything is charged — pick another local number. If the balance cannot pay a month, the number is kept for 30 days, still answering calls while the balance allows; after that it is released, and a released number cannot be recovered. A call on a number is billed like any agent session (platform time per second and the language model per token) plus the phone line **per started minute**, by direction and country: a call your agent **receives** is priced by the country of your number, one it **makes** ([dial](#post-/callcenter/dial-—-place-one-outbound-call), [bulk dial](#post-/callcenter/bulk-dial-—-create-a-bulk-dial-batch)) by the destination, landline or mobile. For example, a received call on a Spanish number is $0.035 a minute of line, about 8.7¢ a minute in all; a call made to a Spanish mobile is $0.105 a minute of line, about 15.7¢ in all. Every country's rate is in [Pricing and billing](/pricing#phone-calls) and in the [rate card](/api-reference/rate-card). A call to your number while the balance is under \$0.25 is not answered. ### Request ```json theme={null} { "phone_number": "+14755750358", "agent_id": "34da7ae3-0d46-4827-8739-ca6a25dc756c" } ``` | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `phone_number` | `string` | Yes | Exact E.164 number from a prior search | | `agent_id` | `string` | No | Bind inbound calls on this number to an agent immediately | ### Response (200) The number was purchased and is already showing as owned. ```json theme={null} { "id": "1234567890", "phone_number": "+14755750358", "agent_id": "34da7ae3-0d46-4827-8739-ca6a25dc756c" } ``` ### Response (202) The order was placed, but Telnyx hasn't finished activating it yet (the API polls briefly, then gives up and returns this instead of blocking indefinitely). It'll show up in [`GET /callcenter/numbers`](#get-/callcenter/numbers-—-list-owned-numbers) shortly after. ```json theme={null} { "phone_number": "+14755750358", "agent_id": "", "note": "order placed, but the number isn't showing as owned yet — it should appear in My Numbers shortly" } ``` ### cURL ```bash theme={null} curl -X POST https://api.lokutor.com/callcenter/numbers \ -H "Authorization: Bearer $LOKUTOR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"phone_number": "+14755750358", "agent_id": "34da7ae3-0d46-4827-8739-ca6a25dc756c"}' ``` *** ## `POST /callcenter/numbers/{id}/assign` — Assign a Number to an Agent Rebinds an already-owned number to route inbound calls to a different agent (or, with `agent_id: ""`, no agent). ### Request ```json theme={null} { "agent_id": "34da7ae3-0d46-4827-8739-ca6a25dc756c" } ``` ### Response ```json theme={null} { "phone_number": "+14755750358", "agent_id": "34da7ae3-0d46-4827-8739-ca6a25dc756c" } ``` *** ## `DELETE /callcenter/numbers/{id}` — Release a Number Releases the number back to Telnyx and removes its agent binding. `{id}` is the Telnyx number ID from [`GET /callcenter/numbers`](#get-/callcenter/numbers-—-list-owned-numbers) (`n.id`), not the phone number itself. > [!WARNING] > > This is irreversible — you lose the number. ### Response ```json theme={null} { "deleted": "1234567890" } ``` *** ## `POST /callcenter/dial` — Place One Outbound Call ### Request ```json theme={null} { "from": "+14755750358", "to": "+15551234567", "agent_id": "34da7ae3-0d46-4827-8739-ca6a25dc756c", "consent_confirmed": true, "context": "Following up on the quote sent Tuesday" } ``` | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `from` | `string` | Yes | A number you own (E.164) | | `to` | `string` | Yes | Destination number (E.164) | | `agent_id` | `string` | No | Which agent answers when the call connects | | `consent_confirmed` | `boolean` | **Yes** | Must be explicitly `true` — see below | | `context` | `string` | No | Free-text injected into the agent's prompt for this call only, never persisted elsewhere | There is no `connection_id` field: calls always go out through Lokutor's outbound profile, which carries the destination-rate limits below. A `connection_id` in the body is ignored. An outbound call is billed as agent time and tokens plus the line per started minute at the destination's rate ([Pricing and billing](/pricing#phone-calls)); a call nobody answers costs nothing. Placing calls needs a first top-up (`402` `billing.topup_required` before it). You can call landlines in every supported country, and mobiles in Spain, France, Germany, Austria, the UK, Ireland, the US and Canada. Mobiles in Portugal, Italy, the Netherlands, Belgium, Luxembourg and Switzerland are above the carrier rate Lokutor allows: dialling one returns `400` with that reason, and nothing is billed. > [!WARNING] > > `consent_confirmed` isn't a default-true convenience flag — omit it or send `false` and the request is rejected with `400`. It asserts you have a lawful basis to make this specific call (consent, an existing business relationship, etc.) and is written to an audit log (`call_consent_log`) alongside the call. It documents that you made the assertion; it doesn't verify it. Outbound calling still needs a real consent/TCPA policy behind it — this is a gate and a paper trail, not a compliance program. ### Response ```json theme={null} { "call_id": "v3:AAAA...", "from": "+14755750358", "to": "+15551234567", "agent_id": "34da7ae3-0d46-4827-8739-ca6a25dc756c" } ``` ### cURL ```bash theme={null} curl -X POST https://api.lokutor.com/callcenter/dial \ -H "Authorization: Bearer $LOKUTOR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"from":"+14755750358","to":"+15551234567","agent_id":"34da7ae3-...","consent_confirmed":true}' ``` Use the returned `call_id` to [follow the call](#get-/callcenter/call-monitor-—-follow-a-call) or hang it up with [`POST /callcenter/hangup/{id}`](#hang-up-a-call). *** ## `GET /callcenter/call-monitor` — Follow a Call `GET /callcenter/call-monitor?call_id={call_id}` returns the current state of a call your account placed: ```json theme={null} { "status": "connected", "transcript": [ "…" ], "duration": 42, "end_reason": "" } ``` `status` is `dialing`, `ringing`, `connected` or `ended`. A call that is not yours, or that the server does not know, reads as `{"status": "ended", "transcript": [], "duration": 0}`. ### Live updates (Server-Sent Events) `GET /callcenter/sse/call-monitor?call_id={call_id}` streams the same information. The first event is a `snapshot` (`status`, `transcript`, `duration`); then `status`, `transcript` (one new line in `text`), `transcript_sync` (the whole `transcript`) and `ended` (with `end_reason`) events follow as the call progresses. Each arrives as a `data:` line holding a JSON object with a `type` field. A `: heartbeat` comment is sent every 15 seconds. A browser `EventSource` cannot send headers, so pass a short-lived ticket (minted on your backend, see [Authentication](/authentication#short-lived-tickets)) as `api_key`: ```typescript theme={null} const { ticket } = await fetch('/api/lokutor-ticket', { method: 'POST' }).then((r) => r.json()); const events = new EventSource( `https://api.lokutor.com/callcenter/sse/call-monitor?call_id=${encodeURIComponent(callId)}&api_key=${ticket}` ); events.onmessage = (e) => { const msg = JSON.parse(e.data); if (msg.type === 'transcript') console.log(msg.text); if (msg.type === 'ended') events.close(); }; ``` *** ## Hang Up a Call `POST /callcenter/hangup/{id}` hangs up a call your account placed. `{id}` is the `call_id` from [`/callcenter/dial`](#post-/callcenter/dial-—-place-one-outbound-call). ```bash theme={null} curl -X POST "https://api.lokutor.com/callcenter/hangup/$CALL_ID" \ -H "Authorization: Bearer $LOKUTOR_API_KEY" ``` ```json theme={null} { "status": "hangup_sent" } ``` *** ## `POST /callcenter/bulk-dial` — Create a Bulk Dial Batch Queues up to 500 calls at once. Each row dials independently, at its own scheduled time (or immediately) — this runs server-side on a background scheduler, so it keeps going even if you close the tab, and even the "dial now" rows go through the same pacing as scheduled ones. ### Request ```json theme={null} { "from": "+14755750358", "agent_id": "34da7ae3-0d46-4827-8739-ca6a25dc756c", "name": "September follow-ups", "consent_confirmed": true, "rows": [ { "phone_number": "+15551234567", "name": "Jane Doe", "context": "Renewal due Oct 1" }, { "phone_number": "+15557654321", "scheduled_at": "2026-09-10T14:00:00Z" } ] } ``` | Parameter | Type | Required | Description | | :- | :- | :- | :- | | `from` | `string` | Yes | A number you own | | `agent_id` | `string` | No | Agent for every call in this batch | | `name` | `string` | No | Display name for the batch | | `consent_confirmed` | `boolean` | **Yes** | Same rule as `/callcenter/dial` — asserts lawful basis to call *every* number on the list | | `rows` | `array` | Yes | 1–500 rows | | `rows[].phone_number` | `string` | Yes | Destination number | | `rows[].name` | `string` | No | Contact name | | `rows[].context` | `string` | No | Per-call context for the agent's prompt | | `rows[].scheduled_at` | `string` (ISO 8601) | No | When to dial this row — omitted or in the past means "as soon as possible" | ### Response ```json theme={null} { "batch_id": "b3f1...", "rows_created": 2 } ``` *** ## `GET /callcenter/bulk-dial` — List Batches Returns every batch created by the authenticated account, most recent first, each with a live status breakdown. ### Response ```json theme={null} { "batches": [ { "id": "b3f1...", "from_number": "+14755750358", "name": "September follow-ups", "created_at": "2026-09-04T12:00:00Z", "row_counts": { "pending": 1, "dialing": 0, "sent": 1, "failed": 0 }, "total_rows": 2 } ] } ``` *** ## `GET /callcenter/bulk-dial/{id}` — Batch Detail Returns one batch with every row, each annotated with its conversation summary once the call has happened. ### Response ```json theme={null} { "id": "b3f1...", "from_number": "+14755750358", "rows": [ { "id": "r1...", "phone_number": "+15551234567", "contact_name": "Jane Doe", "status": "sent", "scheduled_at": "2026-09-04T12:00:01Z", "conversation": { "...": "see Conversation object" } } ] } ``` Row `status` is one of `pending`, `dialing`, `sent`, `failed`. *** ## Related Pages * [Phone agent quickstart](/guides/phone-agent-quickstart): buy a number and take a call * [Errors](/api-reference/errors): error codes, including the billing `402`s * [REST API](/api-reference/rest): synthesis, transcription and discovery endpoints * [My First Agent](/guides/my-first-agent): build an agent to route these calls to # Error Catalog Source: https://docs.lokutor.com/api-reference/errors Every Lokutor error code with its HTTP status and retryable flag, where each one is sent, the synthesis 503 shape, billing 402s, WebSocket close codes, and retry handling with the SDK. All Lokutor API errors follow a single structured format: ```json theme={null} { "code": "auth.invalid_key", "message": "The provided API key is invalid or has been revoked.", "detail": "Key sk_xxx...xxxx failed validation", "retryable": false } ``` | Field | Type | Description | | :- | :- | :- | | `code` | `string` | Machine-readable identifier. Use this in switch statements. | | `message` | `string` | Human-readable explanation suitable for UI display. | | `detail` | `string` | Additional context (may contain request-specific data). | | `retryable` | `boolean` | Whether the client should retry the request. | On WebSockets the same object arrives inside an error frame: `{"type": "error", "data": {"code", "message", "detail", "retryable"}}`. On `/ws/agent` and `/ws/stt`, some runtime errors carry a plain string in `data` instead (`{"type": "error", "data": "AI response service error."}`); handle both. Two responses do not use this shape: the synthesis capacity `503` ([below](#synthesis-at-capacity)) and the Call Center API's billing errors ([below](#billing-errors)). *** ## Authentication Errors Errors that indicate the client cannot authenticate. Do **not** retry these without user intervention. | Code | HTTP Status | Meaning | | :- | :- | :- | | `auth.missing_key` | `401` | No credential was provided. Send an API key or `wst_` ticket as `Authorization: Bearer `, `X-API-Key: `, or `?api_key=`; every authenticated endpoint accepts all three. | | `auth.invalid_key` | `401` | The API key is invalid, expired, or revoked. | | `auth.rate_limited` | `429` | Too many requests from this IP or key, or too many sessions open at once ("Too many concurrent sessions": 3 per account before the first top-up, 10 after, see [Limits](/pricing#limits)). Wait and retry with backoff, or close a session. | | `auth.time_limited` | `429` | Demo time limit reached. Obtain a production API key. | **SDK handling:** ```typescript theme={null} client.on('error', (error) => { if (error.code === 'auth.invalid_key') { showLoginModal(); } if (error.code === 'auth.rate_limited') { showToast('Too many sessions open. Close one or wait.'); } }); ``` You can also pass `onError` to the client's constructor. It is a constructor option, not a property to assign later. *** ## Validation Errors Errors that indicate the request was malformed. Fix the request payload and retry. | Code | HTTP Status | Meaning | | :- | :- | :- | | `validation.invalid_voice` | `400` | The requested voice style does not exist. | | `validation.invalid_language` | `400` | The requested language is not supported. | | `validation.text_too_long` | `400` | The request is too big: more than 5,000 characters (on `POST /tts/synthesize`, counted across `text` and every segment), more than 200 segments, a `pause_ms` outside 0–10,000, or more than 60,000 ms of pauses in total. The `message` says which. | | `validation.speed_out_of_range` | `400` | `speed` outside 0.5–2.0 on `/ws/tts`. (`POST /tts/synthesize` resets it to 1.0 instead.) | | `validation.steps_out_of_range` | `400` | `steps` above 128 on `/ws/tts`. (`POST /tts/synthesize` treats anything above 8 as 8 instead.) | | `validation.invalid_request_format` | `400` | The request could not be used: unparseable JSON, a missing required field (`text`, `voice`), a body over 1 MB, or audio that is not an accepted WAV format or is over 10 MB (`/stt/transcribe`, `/denoise`). | *** ## TTS Errors | Code | HTTP Status | Meaning | Retryable | | :- | :- | :- | :- | | `tts.synthesis_failed` | `503` | Synthesis failed on Lokutor's side. On `/ws/tts` the error frame is followed by `EOS`, and the message is not billed. | Yes | | `tts.session_limit_reached` | `503` | The server cannot start another voice-agent session right now. This limit is shared by all accounts; your account's own session limit answers `auth.rate_limited`. | Yes | ### Synthesis at capacity When every synthesis slot is busy, `POST /tts/synthesize` answers `503` with a `Retry-After` header (seconds) and a body that is **not** the error-catalog shape: ```json theme={null} { "error": "synthesis capacity reached, retry shortly", "voice": "F1", "hint": "every stream slot on this worker is in use; the request was not malformed" } ``` Wait `Retry-After` seconds and send the same request again. *** ## Agent Errors | Code | HTTP Status | Meaning | Retryable | | :- | :- | :- | :- | | `agent.provider_error` | `503` | An upstream service failed: on `/denoise`, the denoiser is unavailable or failed; in agent sessions, the language model or synthesis. | Yes | | `agent.not_found` | `404` | The `agent_id` does not exist or belongs to another account. A session may only use your own agents. Sent at the `/ws/agent` handshake. | No | *** ## Billing Errors Usage is paid from a prepaid balance ([Pricing and billing](/pricing)). These errors mean the account cannot pay for what was asked; none of them goes away by retrying. | Code | HTTP Status | Meaning | Retryable | | :- | :- | :- | :- | | `billing.insufficient_balance` | `402` | The balance is below \$0.25, the minimum to start a session or request (or, when buying a phone number, below its first month). The message states the balance. Top up in the dashboard (**Billing**), or turn on auto-recharge. | No | | `billing.topup_required` | `402` | Calls your agent makes to phones (`/callcenter/dial`, bulk dial) and phone numbers need a first top-up: the welcome credit does not pay carriers. | No | | `billing.account_disputed` | `402` | A payment on the account is disputed, and usage is paused until the dispute is resolved. Write to [contact@lokutor.com](mailto:contact@lokutor.com). | No | | `billing.limit_reached` | `402` | Only for accounts still on a monthly plan while accounts move to the balance: the plan's limit (agent minutes, TTS characters or STT minutes, depending on the endpoint) has been reached. | No | Where they arrive: * **REST** (`/tts/synthesize`, `/stt/transcribe`, `/denoise`): in the error format above. * **[Call Center API](/api-reference/call-center)**: as `{"code": "billing.topup_required", "error": "…"}`, with the same codes. * **WebSocket** (`/ws/agent`, `/ws/tts`, `/ws/stt`): the refusal comes before the connection opens. The handshake answers `402` with the message as plain text; a browser `WebSocket` only sees the connection fail (close code `1006`), so check the balance when a connection fails at the handshake. A call already in progress is not cut with an error when the balance runs out: the agent says goodbye and hangs up once the account is \$2 below zero, and on the web the socket then closes with `1008` and the reason `account balance exhausted`. See [When the balance runs out](/pricing#when-the-balance-runs-out). *** ## Internal Errors | Code | HTTP Status | Meaning | Retryable | | :- | :- | :- | :- | | `internal.error` | `500` | An unexpected error occurred. | Yes | ## Reserved codes These codes are defined, and appear in the SDKs' `ErrorCode` type, but the server does not send them today. Handle them generically (by `retryable`) if you match on codes exhaustively. | Code | HTTP Status | `retryable` | | :- | :- | :- | | `tts.voice_unavailable` | `503` | `true` | | `tts.model_not_found` | `503` | `true` | | `stt.not_configured` | `503` | `true` | | `stt.stream_create_failed` | `500` | `true` | | `stt.language_not_supported` | `503` | `true` | | `agent.session_failed` | `503` | `true` | | `internal.timeout` | `504` | `true` | | `internal.cancelled` | `400` | `false` | The JavaScript SDK's `TTSClient` uses `internal.timeout` for its own client-side timeout (no audio within 30 s, or 15 s without a chunk); that one is never sent by the server. ## Client-side codes (JavaScript SDK) These are raised by `@lokutor/sdk` itself, not sent by the server. | Code | Meaning | Retryable | | :- | :- | :- | | `audio.microphone_unavailable` | The microphone could not be started: permission refused (`detail` starts with `NotAllowedError`), no device (`NotFoundError`), or another capture failure. `connect()` rejects with it and the session is closed. | No | | `session.ended` | The server closed the session on purpose (close code 1000, 1008 or 4xxx); `message` is the server's reason. The SDK does not reconnect. | No | | `ws.close` | The WebSocket failed or closed before the session was established. | Depends on the close code | *** ## WebSocket Close Codes When the connection closes, the WebSocket close code provides additional context: | Code | Name | Meaning | Retryable | | :- | :- | :- | :- | | `1000` | Normal | Clean closure by client or server, including a session nobody has spoken on for 5 minutes (reason `nobody has spoken for 5 minutes`). | No | | `1001` | Going Away | Server is shutting down or client navigated away. | Yes | | `1006` | Abnormal | Connection dropped unexpectedly (network issue, auth failure, CORS). | Yes | | `1008` | Policy Violation | Rate limit or usage policy violated, or the account's balance ran out during the session (reason `account balance exhausted`). | No | | `1011` | Server Error | Internal server error caused the close. | Yes | *** ## Retry Strategy Decide from `retryable`, and treat `402` (`billing.*`) as a prompt to top up rather than an error to retry. A complete recipe is in [Error handling](/guides/error-handling). ```typescript theme={null} import { VoiceAgentClient, isRetryable } from '@lokutor/sdk'; const client = new VoiceAgentClient({ auth: getTicket, agentId: 'your-agent-id' }); client.on('error', (error) => { if (error.code.startsWith('billing.')) { showTopUpPrompt(error.message); // https://app.lokutor.com/billing return; } if (!isRetryable(error)) { showErrorModal(error.message); // fix the request, the key or the agent return; } // Retryable. After a dropped connection the SDK reconnects by itself, up to 5 times // (2 s, 4 s, 8 s, 10 s, 10 s). A session the server ended on purpose arrives as // 'session.ended' and is not retried. console.warn('Transient error:', error.code, error.message); }); ``` ### Custom retry logic If you connect yourself rather than relying on the SDK's reconnection: ```typescript theme={null} import { isRetryable } from '@lokutor/sdk'; const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); async function connectWithRetry(client: { connect(): Promise }, maxRetries = 5) { for (let attempt = 1; ; attempt++) { try { return await client.connect(); } catch (error) { if (!isRetryable(error) || attempt >= maxRetries) throw error; const delay = Math.min(1000 * 2 ** attempt, 10000); await sleep(delay + Math.random() * 1000); // jitter } } } ``` *** ## Related Pages * [Error handling recipe](/guides/error-handling) * [JavaScript SDK Reference](/sdks/javascript/reference#error-handling) * [WebSocket Protocol](/guides/websocket-protocol) * [Troubleshooting](/sdks/troubleshooting) # Expression tags Source: https://docs.lokutor.com/api-reference/expression-tags Make the voice breathe, laugh or sigh, or speak a sentence happy, sad, angry and more: the sound tags and emotion tags in the text of a synthesis request or an agent reply An expression tag is a word in square brackets, written in the text, that the voice **performs** instead of reading. There are two kinds: **sound tags** (a breath, a laugh, a sigh) and **emotion tags** (the sentence is spoken happy, sad, angry and so on). ```text theme={null} I can't believe that. [laugh] ``` Tags work anywhere you send text to be spoken: `POST /tts/synthesize`, the `/ws/tts` WebSocket, and a voice agent's replies and first message wherever the agent writes them. ## The tags | Tag | What the voice does | | :- | :- | | `[breath]` | Takes a breath. | | `[laugh]` | Laughs. | | `[sigh]` | Sighs. | ### Emotion tags > [!NOTE] > > Emotion tags are deliberately **subtle**: since 4 November 2026 the voice moves a sentence only part of the way towards the emotion, so it blends with the plain sentences around it instead of jumping in pitch. Sound tags are unchanged. | Tag | The sentence it opens is spoken | | :- | :- | | `[happy]` | happy | | `[sad]` | sad | | `[angry]` | angry | | `[surprised]` | surprised | | `[fearful]` | fearful | | `[disgusted]` | with disgust | | `[excited]` | excited | | `[anxious]` | anxious | An emotion tag goes at the **start** of the sentence it colours: `[sad] I'm sorry to hear that.` It affects that sentence only; the next one is spoken normally unless it has its own tag. Emotion tags change how the sentence is spoken and barely change its length. Emotion tags are strongest in English. In Spanish the effect is milder, and other languages are untested, so listen to the result before you ship it. The effect also depends on the voice and varies a little from render to render. A mild, natural effect is the goal: they do not turn a calm voice into a shout. Tags are case-insensitive: `[Laugh]` and `[HAPPY]` are the same as `[laugh]` and `[happy]`. ## Using them * Put a sound tag **after the sentence's full stop**: `I can't believe that. [laugh]`. This gives the best results. Put an emotion tag **before** the sentence it colours: `[excited] We won!`. * A sound tag **stays with the sentence before it**. Long text is spoken sentence by sentence, and `Okay. [laugh] That's it! [sigh] Fine.` is spoken as `Okay. [laugh]`, `That's it! [sigh]`, `Fine.`. A tag is never synthesized on its own. * An emotion tag **stays with the sentence after it**: `Okay. [sad] I'm sorry about that.` is spoken as `Okay.` and `[sad] I'm sorry about that.` * A tag at the very start of the text stays with the first sentence: `[laugh] Hi there.` * Tags are not read as words, and they are not touched by numbers, symbols or [pronunciation](/api-reference/pronunciation) rules. * A tag counts as characters of the request text, like any other text. ## A sound tag adds time The clip is longer than the same text without the sound tag (emotion tags barely change it). Measured on our renders: | Tag | Added time | | :- | :- | | `[breath]` | about 2 s | | `[laugh]` | 2–4 s, occasionally up to 7 s | | `[sigh]` | about 1.5 s | Every tagged test render was longer than its untagged twin, and none ran away. Leave room for the extra time in anything timed to the text, such as captions or a fixed-length slot. ## Examples ### `POST /tts/synthesize` ```json theme={null} { "text": "I can't believe that. [laugh] Anyway, let me check your order. [breath]", "voice": "F1", "language": "en" } ``` ### WebSocket (`/ws/tts`) ```json theme={null} { "text": "That was a long day. [sigh] Let's start again.", "voice": "M1", "language": "en" } ``` ### Voice agents Ask for them in the agent's prompt, for example: "When the caller makes a joke, answer with a short laugh by ending your sentence with `[laugh]`." They also work in the agent's first message, written verbatim. Or let the agent decide, with every tag explained to it, using the `expression_tags` setting, below. ## The `expression_tags` agent setting Voice agents can use every tag on this page on their own. Turn it on per agent with `expression_tags` in the agent's `config`. | Field | Type | Default | | :- | :- | :- | | `expression_tags` (in the agent's `config`) | boolean | `false` when the key is absent | In the dashboard: agent settings, Behaviour, "Expression tags". Agents created in the dashboard start with it on; existing agents are unchanged until you switch it on. A change applies to the next call. * When on, the agent's language model is told what every tag means and uses them where a person's voice would change: a sound where something is funny or sympathetic (`[laugh]`, `[sigh]`, `[breath]`), an emotion at the start of the sentence it colours (`[happy] Great news, it is confirmed.`). `[happy]` and `[excited]` are for good news, `[sad]` for sympathy or bad news, `[surprised]` for the unexpected, `[anxious]` for real urgency. `[angry]`, `[fearful]` and `[disgusted]` mean the agent itself feels it, so they are only for a character written that way, and the model is told to sympathise with an upset caller with `[sad]` or `[sigh]`, never `[angry]`. Emotions are milder outside English. * It also acknowledges what the caller says with short spoken sounds written as plain words, like "Aha, I see.", "Hmm, let me think.", "Oh, okay!", "Ah, right." and, in Spanish, "Ajá, entiendo.". * There is no fixed frequency: the model decides, and your own prompt wins where it conflicts. To make an agent more or less expressive, say so in its prompt; to get no tags at all, leave the setting off. * Tags never appear in transcripts, call summaries, evaluations or webhooks. The agent itself still sees them in its own conversation history, so it does not repeat them. * Only the tags listed on this page reach the voice. Anything else in square brackets in a reply is removed before speech, so a malformed tag is never read aloud, and an emotion tag with no words after it is dropped. * The instructions that enable this add about 270 tokens to every model request of that agent, which counts toward its language-model token usage (billed like any other tokens). Billing for speech is not affected by the tag itself, but sound tags add speech time (see above). * Typing a tag in your own text (first message, TTS API) is unaffected by this setting. ## Tips * One tag where it matters sounds natural; a tag on every sentence does not. * Use `[breath]` before a long or serious answer, `[sigh]` for sympathy, `[laugh]` after something funny. * Write the tag after the full stop, not in the middle of a sentence. ## Limitations * Only the eleven tags on this page exist. An unknown bracketed word such as `[giggle]` is not a tag: it is **read as plain text**, as written. * If the voice engine serving your request does not support tags (for example after a rollback), the tag is **dropped silently** and is never spoken as a word. The rest of the text is spoken as usual. * Long laughs are the weakest case, and are being improved. The duration of a laugh varies from render to render. * Tags do not change the voice or language. Emotion tags are English-first (see above). # Live Translation Source: https://docs.lokutor.com/api-reference/live-translation Speech-to-speech translation over WebSocket (wss://api.lokutor.com/v1/ws/translate): config, audio in, transcripts, translations and translated audio out, incremental mode, latency frames, errors, capacity and pricing A speaker talks in one language and listeners hear translated speech in another, a phrase behind, keeping the intent, register and tone of what was said (irony stays irony). The output voice is any voice your account can use for text-to-speech: a stock voice or one of your cloned voices. ## Connection ``` wss://api.lokutor.com/v1/ws/translate ``` `/ws/translate` is the same endpoint. Authenticate the handshake as for [`/ws/tts`](/api-reference/streaming#connection): an `Authorization: Bearer` or `X-API-Key` header, or `?api_key=` where headers cannot be set. In a browser, pass a short-lived `wst_` ticket rather than your key ([Authentication](/authentication)). One translation session holds one concurrent-session slot of your account, the same pool as text-to-speech sockets. ## Messages ### Client to server: config The first message, within 10 seconds of connecting: ```json theme={null} { "type": "config", "source_language": "es", "target_language": "en", "voice": "en_f1", "input_rate": 16000, "output_rate": 44100, "tone": "relaxed, dry humour" } ``` | Field | Required | Meaning | | :- | :- | :- | | `source_language` | no | Language spoken. `""` (or omitted) detects it and follows the speaker if they switch. A named language is always used as given. | | `target_language` | yes | Language of the translated speech. Must differ from `source_language`. | | `voice` | no | Stock voice id or one of your cloned voices (`clone_...`). Empty: the default voice for the target language. | | `input_rate` | no | Sample rate of your PCM. Default 16000. One of 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000. | | `output_rate` | no | Sample rate of the audio you get back. Default 44100, same set of rates. | | `incremental` | no | Default `true`: the speaker is translated while still talking (below). `false` translates each phrase after the speaker's pause. | | `tone` | no | A free-text hint about how the speaker talks, at most 300 characters. It guides delivery; it does not change what is said. | Languages: `es`, `ca`, `gl`, `eu`, `en`, `fr`, `de`, `it`, `pt` (`GET /languages`). ### Client to server: audio Binary frames of the speaker's microphone: PCM16 little-endian, mono, at `input_rate`, any frame size (20-100 ms is typical). Send them as you capture them, continuously; silence is fine. Phrases are cut at the speaker's pauses. `{"type":"end"}` (text) finishes the session: the phrase in progress is translated, everything queued is spoken, then the server sends `{"type":"end"}` and closes. Closing the socket stops everything at once. ### Server to client | Message | Meaning | | :- | :- | | `{"type":"ready","session_id":"...","input_rate":16000,"output_rate":44100}` | Config accepted; start sending audio. | | `{"type":"transcript","seq":1,"text":"...","language":"es","final":false}` | Incremental mode only: a clause of phrase `seq` that was committed and sent to translation. | | `{"type":"transcript","seq":1,"text":"...","language":"es","final":true}` | What the speaker said in the whole phrase, in the source language (`language` is the one used). One per phrase; it replaces the `final:false` pieces. | | `{"type":"translation","seq":1,"text":"...","final":false}` | A piece of the translation as it is produced. | | `{"type":"translation","seq":1,"text":"","final":true}` | The complete translation of phrase `seq`, sent when the phrase has ended. | | binary frame | PCM16 mono at `output_rate`: the translated speech. Frames arrive in phrase order, as soon as each sentence or clause is ready. | | `{"type":"latency", ...}` | After phrase `seq` has been spoken (below). | | `{"type":"error","data":{"code","message","detail","retryable"}}` | Same structure as the other WebSockets ([Errors](/api-reference/errors)). | | `{"type":"end"}` | The session is finished (after your `end`). | `seq` numbers phrases from 1. The speaker can keep talking while earlier phrases are still being spoken: their transcripts arrive immediately and their audio queues behind the current one. Nothing is reordered or dropped silently. If the backlog grows past 64 phrases, a phrase is dropped and an `error` says so. If a phrase is already in the target language it is not translated; the words are spoken as they are. ### Incremental mode (default) While the speaker talks, the server re-transcribes the growing phrase about every 500 ms. Words that two consecutive transcripts agree on (less the last two, which are the least reliable) are *committed* and translated as a clause, cut at punctuation or after about six words, as a sentence in progress so the translation continues naturally. Audio already sent is never retracted or repeated: committed words are final. When the speaker pauses, the whole phrase is transcribed once more and only the words after the committed ones are translated. Expect the first translated audio to start before the speaker has finished the sentence. The cost is that a clause is translated before the rest of the sentence is known, so word order and nuance can be a little less polished than with `incremental: false`. At most one extra recognition request per session is in flight at a time, and none are made for the part of a phrase beyond 12 s of speech (the final transcription covers it). ### Latency frames ```json theme={null} {"type":"latency","seq":1,"source_language":"es","partials":4,"stt_ms":120,"llm_first_token_ms":210,"first_audio_from_start_ms":2700,"first_audio_ms":-300,"total_ms":900} ``` | Field | Meaning | | :- | :- | | `partials` | Recognition requests made while the phrase was spoken. | | `stt_ms` | End of speech to the final transcript. | | `llm_first_token_ms` | First text handed to translation to the first translated token. | | `first_audio_from_start_ms` | First audio, measured from the start of the speech. | | `first_audio_ms` | First audio, measured from the end of the speech. Negative when audio started before the speaker finished. | | `total_ms` | End of speech to the last audio. | Fields are `null` when not measured (no audio). The values above only show the shape. One production test (2026-10-27) measured the first translated audio about 2.7 s after the speaker starts, and the median about 0.25 s after a sentence ends. That is one test, not a guarantee: read the `latency` frames of your own sessions. ## Errors | `code` | When | | :- | :- | | `validation.invalid_request_format` | First message is not a config; unsupported `input_rate` or `output_rate`; `tone` too long; unknown message type. Closes if during config. | | `validation.invalid_language` | Missing or unknown `target_language`, unknown `source_language`, or both equal. | | `validation.invalid_voice` | Unknown voice, or a cloned voice that is not yours. | | `auth.rate_limited` | Too many concurrent sessions for your account. | | `agent.provider_error` | Recognition or translation failed for one phrase (the session continues). | | `tts.synthesis_failed` | Synthesis failed or is unavailable for one phrase (the session continues). | Two refusals come before the WebSocket opens, as plain HTTP responses on the handshake: | Status | When | | :- | :- | | `402` | Your balance cannot start a session. [Top up](/pricing). | | `503` | `live translation is at capacity, try again in a moment`: see below. Retry shortly. | ## Concurrency and capacity Your sessions count against your account's concurrent-session limit, the same pool as text-to-speech sockets (`auth.rate_limited` past it). Separately, the number of translation sessions in flight is capped across all customers, because each session asks the shared recognition service for about 1.5 requests per second of speech and a few sessions would slow every voice agent. When the cap is reached, new connections get the `503` above until a session ends. Treat it as retryable, with a short backoff. If you need guaranteed capacity for an event, contact us in advance. ## Pricing **\$0.055 a minute of speech, all-in** (before tax; `translation_per_minute` on the [rate card](/api-reference/rate-card), `GET /v1/pricing`), charged per second of session time from the moment the socket is accepted until it closes. The price includes recognition, the translation model and the synthesized voice: no tokens, characters or speech-to-text seconds are charged on top, and the session is not billed as a text-to-speech socket. It is debited from your prepaid wallet like the other usage lines and appears as a `translation` line in your usage. A session left open with nobody talking is still a session: send `end` or close the socket when you are done. ## Example: translate a WAV file Streams a 16-bit mono 16 kHz WAV file at real-time pace and saves the translated speech as a WAV file. ```javascript JavaScript (Node 22, ws) theme={null} import WebSocket from 'ws' import fs from 'node:fs' const KEY = process.env.LOKUTOR_API_KEY const wav = fs.readFileSync('speech_es_16k.wav') const pcm = wav.subarray(44) // assumes a plain 44-byte header, PCM16 mono 16 kHz const OUT_RATE = 44100 const ws = new WebSocket('wss://api.lokutor.com/v1/ws/translate', { headers: { 'X-API-Key': KEY } }) const audio = [] ws.on('open', () => ws.send(JSON.stringify({ type: 'config', source_language: 'es', target_language: 'en', voice: 'en_f1', input_rate: 16000, output_rate: OUT_RATE, }))) ws.on('message', async (data, isBinary) => { if (isBinary) { audio.push(data); return } const m = JSON.parse(data.toString()) if (m.type === 'ready') { const frame = 16000 * 2 * 0.02 // 20 ms of PCM16 for (let i = 0; i < pcm.length; i += frame) { ws.send(pcm.subarray(i, i + frame)) await new Promise(r => setTimeout(r, 20)) // real-time pace } ws.send(JSON.stringify({ type: 'end' })) } else if (m.type === 'transcript' && m.final) console.log('heard:', m.text) else if (m.type === 'translation' && m.final) console.log('said :', m.text) else if (m.type === 'error') console.error(m.data) else if (m.type === 'end') { const body = Buffer.concat(audio) const h = Buffer.alloc(44) h.write('RIFF', 0); h.writeUInt32LE(36 + body.length, 4); h.write('WAVEfmt ', 8) h.writeUInt32LE(16, 16); h.writeUInt16LE(1, 20); h.writeUInt16LE(1, 22) h.writeUInt32LE(OUT_RATE, 24); h.writeUInt32LE(OUT_RATE * 2, 28) h.writeUInt16LE(2, 32); h.writeUInt16LE(16, 34); h.write('data', 36); h.writeUInt32LE(body.length, 40) fs.writeFileSync('translated.wav', Buffer.concat([h, body])) ws.close() } }) ``` ```python Python (websockets) theme={null} import asyncio, json, os, wave import websockets KEY = os.environ["LOKUTOR_API_KEY"] OUT_RATE = 44100 async def main(): with wave.open("speech_es_16k.wav", "rb") as w: # PCM16 mono 16 kHz pcm = w.readframes(w.getnframes()) frame = 16000 * 2 * 20 // 1000 # 20 ms of PCM16 audio = bytearray() # websockets >= 14 uses additional_headers; older versions use extra_headers async with websockets.connect("wss://api.lokutor.com/v1/ws/translate", additional_headers={"X-API-Key": KEY}) as ws: await ws.send(json.dumps({"type": "config", "source_language": "es", "target_language": "en", "voice": "en_f1", "input_rate": 16000, "output_rate": OUT_RATE})) assert json.loads(await ws.recv())["type"] == "ready" async def send_file(): for i in range(0, len(pcm), frame): await ws.send(pcm[i:i + frame]) await asyncio.sleep(0.02) # real-time pace await ws.send(json.dumps({"type": "end"})) sender = asyncio.create_task(send_file()) async for msg in ws: if isinstance(msg, bytes): audio += msg continue m = json.loads(msg) if m["type"] == "transcript" and m["final"]: print("heard:", m["text"]) elif m["type"] == "translation" and m["final"]: print("said :", m["text"]) elif m["type"] == "error": print("error:", m["data"]) elif m["type"] == "end": break await sender with wave.open("translated.wav", "wb") as out: out.setnchannels(1); out.setsampwidth(2); out.setframerate(OUT_RATE) out.writeframes(bytes(audio)) asyncio.run(main()) ``` # OpenAPI Spec Source: https://docs.lokutor.com/api-reference/openapi-spec The Lokutor HTTP API as an OpenAPI 3.1 document (synthesis, transcription, denoising, tickets, discovery, Call Center), for code generation, API clients and AI tooling. The HTTP API documented in this section ([TTS synthesis](/api-reference/rest#post-/tts/synthesize-—-tts-synthesis), [STT transcription](/api-reference/rest#post-/stt/transcribe-—-speech-to-text), denoising, `POST /ws-ticket`, the [discovery endpoints](/api-reference/rest#discovery) and the [Call Center API](/api-reference/call-center)) is published as one OpenAPI 3.1 document: ``` https://docs.lokutor.com/api-reference/openapi.json ``` Use it to: * Generate a typed client in any language (`openapi-generator`, `openapi-typescript`, etc.) * Point an OpenAPI-aware MCP or agent tool at Lokutor's REST API directly * Validate requests/responses against a schema in CI > [!NOTE] > > This spec covers the **HTTP** surface only. The real-time voice-agent, TTS and STT protocols run over WebSocket, which OpenAPI does not model; they are documented at [WebSocket Protocol](/guides/websocket-protocol), [Real-time Streaming](/api-reference/streaming), and [Voice Chat](/api-reference/voice-chat). If you are giving an AI assistant the documentation rather than generating a client, use [`llms-full.txt`](https://docs.lokutor.com/llms-full.txt): every page of these docs in one text file, generated from the pages themselves, including the WebSocket protocol. [`llms.txt`](https://docs.lokutor.com/llms.txt) is the index of pages with their descriptions. ### cURL ```bash theme={null} curl -s https://docs.lokutor.com/api-reference/openapi.json | jq '.paths | keys' ``` # Pronunciation Source: https://docs.lokutor.com/api-reference/pronunciation Tell the voice how to say brand names, product names and other terms: pronunciation dictionaries, per-request pronunciations, and markup, and the sampling temperature A pronunciation entry tells the voice how to say a term. You write the term as it should **sound**, in the spelling of the language being spoken: `Lokutor` said as `Lokútor`, `Stranger Things` in Spanish as `Estrénjer Zings`. Entries apply before numbers and symbols are read, so `4K`, `C++` or `COVID-19` can be overridden too. Entries live in **pronunciation dictionaries** on your account, and apply: 1. to every synthesis your account makes, from its **default** dictionary; 2. to an agent's calls, from the dictionaries the agent uses (dashboard: the agent's settings); 3. to one request, from the dictionaries it names and the entries it carries. When several layers have the same term, the higher one wins: a request's own entries, then the dictionaries it names, then the agent's, then the default. ## Writing a good respelling * Write it as it sounds **in the language being spoken**, with that language's letters: Spanish `Guatsáp` for WhatsApp, Catalan or French spellings for those languages. * Mark the stressed syllable with an accent where the language uses one: `Lokútor`. * Lowercase. A short word in capitals (`NASA`) is read letter by letter, so it is rejected. * No digits: they are read as numbers. Write them as words. * Give a respelling per language you need. A term with no respelling for the language being spoken is said as written. ## Entry | Field | Type | Required | Description | | :- | :- | :- | :- | | `term` | string | Yes | The text to replace, 1–64 characters. Matched as a whole word or phrase. | | `say_as` | object | Yes | Respellings by language code, e.g. `{"es": "Lokútor", "fr": "Lokutôr"}`. 1–128 characters each. | | `lang` | string | No | The term's own language (e.g. `en` for an English brand name). Informational today. | | `case_sensitive` | bool | No | `false` by default: `lokutor`, `Lokutor` and `LOKUTOR` all match. | | `enabled` | bool | No | `true` by default. | **Matching.** Longest term first, left to right, one pass (a respelling is never matched again). A term matches only as a whole word: `Teams` matches in `Teams.` and `Teams's`, not in `TeamsPro` or `Teams-like`. In French, Catalan, Italian and Portuguese a term also matches after an elided article or preposition: `l'iPhone`, `d'Amazon`, `dell'App`, `qu'Uber` keep their `l'`, `d'`… and respell only the term. ## Dictionaries Authenticate as for any API call (`Authorization: Bearer` or `X-API-Key`). An account has at most 50 dictionaries of at most 2,000 entries each, and at most one default. ### `GET /v1/pronunciation-dictionaries` ```json theme={null} { "dictionaries": [ { "id": "6f1c…", "name": "Brand names", "is_default": true, "entries": [{"term": "Lokutor", "say_as": {"es": "Lokútor"}}], "created_at": "2026-10-26T19:00:00Z", "updated_at": "2026-10-26T19:00:00Z" } ] } ``` ### `POST /v1/pronunciation-dictionaries` Creates a dictionary. Body: `name` (1–100 characters), `is_default` (making one the default clears the previous one), `entries`. Returns `201` with the dictionary. ```bash theme={null} curl -X POST https://api.lokutor.com/v1/pronunciation-dictionaries \ -H "Authorization: Bearer sk_your_key_here" \ -H "Content-Type: application/json" \ -d '{"name": "Brand names", "is_default": true, "entries": [{"term": "WhatsApp", "say_as": {"es": "Guatsáp"}}, {"term": "Stranger Things", "say_as": {"es": "Estrénjer Zings"}, "lang": "en"}]}' ``` ### `GET`, `PUT`, `DELETE /v1/pronunciation-dictionaries/{id}` `PUT` replaces the dictionary's `name`, `is_default` and `entries` with the body's. `DELETE` removes it; agents that used it simply stop using it. ### Validation Every save is checked by the same text processing the voice uses. A respelling the voice cannot say as written is refused with `400` and the problems found: ```json theme={null} { "error": "some respellings cannot be said as written", "problems": [ {"index": 0, "lang": "es", "level": "error", "message": "'NASA' is in capitals, so it would be spelled out letter by letter; write it in lowercase as it sounds"} ] } ``` `index` is the entry's position. `level` is `error` (not saved) or `warning` (saved: digits, which are read as numbers). A save with warnings and no errors succeeds (`201` or `200`) and returns the dictionary with its warnings under `problems`, in the same shape. ## Per request `POST /tts/synthesize` and `WS /ws/tts` take: | Parameter | Type | Description | | :- | :- | :- | | `pronunciation_dictionary_ids` | string\[] | Dictionaries to apply to this request, in priority order, on top of your default one. Unknown ids are ignored. | | `pronunciations` | Entry\[] | Entries for this request only; they win over every dictionary. A malformed entry is a `validation.invalid_request_format` error. | | `temperature` | number | How varied the delivery is, `0.1`–`1.0`. Default `0.3`. Higher sounds livelier and less predictable. Outside the range is a `validation.invalid_request_format` error. | ```json theme={null} { "text": "Mira el nuevo episodio de Stranger Things en la app.", "voice": "F3", "language": "es", "pronunciations": [{"term": "Stranger Things", "say_as": {"es": "Estrénjer Zings"}}] } ``` ## Markup The `text` of any request may carry: | Markup | Effect | | :- | :- | | `SC` | Says the alias instead of the enclosed text, once. | | `meeting` | Marks a span in another language: entries are looked up with that language's respelling. The span is still read in the request's language; speaking it in its own language mid-sentence is coming. | Anything else that looks like a tag is read as written. To have the voice breathe, laugh or sigh, see [Expression tags](/api-reference/expression-tags). # Rate Card Source: https://docs.lokutor.com/api-reference/rate-card GET /v1/pricing: every price Lokutor charges, as JSON. Public, no key. ## `GET /v1/pricing` — Rate Card Returns the rate card: the price of every line on a Lokutor bill, and the rules of the prepaid balance. It is the one copy of the prices: the dashboard, [lokutor.com/pricing](https://lokutor.com/pricing) and [Pricing and billing](/pricing) all read from it. Public, no API key, CORS open, so a browser page can read it directly. All prices are in US dollars, before tax. How each one is applied (per second, per token, per started minute) is explained in [Pricing and billing](/pricing). ### Response `Content-Type: application/json`, `Cache-Control: public, max-age=300`. ```json theme={null} { "version": "2026-10-09.1", "currency": "USD", "notes": "Prices before tax. …", "agent": { "platform_per_minute": 0.042, "billing": "per_second" }, "llm": { "input_per_million_tokens": 0.44, "output_per_million_tokens": 0.94, "expert_input_per_million_tokens": 1.24, "expert_output_per_million_tokens": 1.87, "speculative_replies_default": true }, "phone": { "billing": "per_started_minute", "inbound": { "ES": 0.035, "PT": 0.025, "FR": 0.028, "IT": 0.035, "DE": 0.028, "AT": 0.028, "CH": 0.028, "BE": 0.035, "NL": 0.035, "LU": 0.025, "GB": 0.025, "IE": 0.025, "US": 0.019, "CA": 0.021 }, "outbound_fixed": { "ES": 0.049, "PT": 0.066, "FR": 0.025, "IT": 0.047, "DE": 0.028, "AT": 0.027, "CH": 0.098, "BE": 0.084, "NL": 0.042, "LU": 0.084, "GB": 0.022, "IE": 0.041, "US": 0.025, "CA": 0.025 }, "outbound_mobile": { "ES": 0.105, "FR": 0.084, "DE": 0.093, "AT": 0.087, "GB": 0.077, "IE": 0.077 }, "number_per_month": 5.0 }, "crm_logged_call": 0.04, "web_search": 0.15, "tts_per_million_chars": 4.1, "stt_per_minute": 0.0014, "denoise_per_minute": 0.0014, "translation_per_minute": 0.055, "wallet": { "min_topup": 10, "max_topup": 2000, "signup_bonus": 5, "signup_bonus_days": 90, "overdraft": 2, "min_session_start": 0.25, "concurrency_default": 10, "concurrency_before_topup": 3, "auto_recharge": { "threshold": 5, "amount": 20, "monthly_cap": 500 } } } ``` ### Fields | Field | Type | Description | | :- | :- | :- | | `version` | `string` | The card's version. A session is charged entirely at the version in force when it started, and your usage records which version it was charged at. | | `currency` | `string` | Always `"USD"`. | | `agent.platform_per_minute` | `number` | A voice-agent session, per minute, billed per second (`agent.billing`). | | `llm.input_per_million_tokens` | `number` | Language-model input tokens, per million. | | `llm.output_per_million_tokens` | `number` | Language-model output tokens, per million. | | `llm.expert_input_per_million_tokens` | `number` | Input tokens of an agent's expert consults, per million ([Expert](/pricing#expert)). | | `llm.expert_output_per_million_tokens` | `number` | Output tokens of an agent's expert consults, per million. | | `llm.speculative_replies_default` | `boolean` | Whether an agent starts replies during the caller's pause unless its config says otherwise (`speculative_llm`). See [Speculative replies](/pricing#speculative-replies). | | `phone.billing` | `string` | `"per_started_minute"`: a phone line is billed by the started minute, on top of the agent. | | `phone.inbound` | `object` | Per minute of a call your agent receives, by the ISO country code of your number. | | `phone.outbound_fixed` | `object` | Per minute of a call your agent makes to a landline, by destination country. | | `phone.outbound_mobile` | `object` | Per minute of a call your agent makes to a mobile, by destination country. A country missing here cannot have its mobiles called, except the US and Canada, whose mobiles are charged the landline rate. | | `phone.number_per_month` | `number` | A phone number, per month, from the balance. | | `crm_logged_call` | `number` | Per call that reaches your CRM (the caller looked up or identified, or the call logged). | | `web_search` | `number` | Per web search that returns an answer. | | `tts_per_million_chars` | `number` | Text-to-speech API, per million characters synthesized. | | `stt_per_minute` | `number` | Speech-to-text API, per minute of audio, billed per second. | | `denoise_per_minute` | `number` | Noise removal (`/denoise`), per minute of audio, billed per second. | | `translation_per_minute` | `number` | Live translation (`/ws/translate`), per minute of session time, billed per second, all-in (recognition, translation and voice). | | `wallet.min_topup`, `wallet.max_topup` | `number` | The smallest and largest top-up in one payment. | | `wallet.signup_bonus`, `wallet.signup_bonus_days` | `number` | The welcome credit and how many days it lasts. | | `wallet.overdraft` | `number` | How far below zero calls in progress may take the balance before the agent says goodbye. | | `wallet.min_session_start` | `number` | The balance needed to start a session or request. | | `wallet.concurrency_default` | `number` | Sessions an account may hold at once after its first top-up. | | `wallet.concurrency_before_topup` | `number` | Sessions an account may hold at once before its first top-up. | | `wallet.auto_recharge` | `object` | Default auto-recharge settings: recharge `amount` when the balance falls below `threshold`, up to `monthly_cap` a month. | New fields may be added; ignore the ones you don't use. ### Example: price a call ```typescript theme={null} const card = await (await fetch('https://api.lokutor.com/v1/pricing')).json(); // A 3-minute call received on a Spanish number, with 62,100 input and 3,900 output tokens. const seconds = 180; const platform = (seconds / 60) * card.agent.platform_per_minute; const tokens = (62_100 * card.llm.input_per_million_tokens + 3_900 * card.llm.output_per_million_tokens) / 1e6; const line = Math.ceil(seconds / 60) * card.phone.inbound.ES; // per started minute console.log((platform + tokens + line).toFixed(3)); // "0.262" ``` ### cURL ```bash theme={null} curl -s https://api.lokutor.com/v1/pricing | jq . ``` # REST API Source: https://docs.lokutor.com/api-reference/rest HTTP endpoints: POST /tts/synthesize (text to WAV, limits and errors), POST /stt/transcribe, POST /denoise, POST /ws-ticket, and the keyless discovery endpoints /voices, /languages, /models, /config, /status, /v1/pricing and /ready. Base URL: `https://api.lokutor.com`. Every route also answers under a `/v1/` prefix (`/v1/tts/synthesize` is the same endpoint as `/tts/synthesize`). | Method | Path | Key | What it does | | :- | :- | :- | :- | | `POST` | [`/tts/synthesize`](#post-/tts/synthesize-—-tts-synthesis) | Yes | Text to a WAV file | | `POST` | [`/stt/transcribe`](#post-/stt/transcribe-—-speech-to-text) | Yes | A recorded clip to text | | `POST` | [`/denoise`](#post-/denoise-—-audio-denoising) | Yes | Remove background noise from a WAV file | | `POST` | [`/ws-ticket`](#post-/ws-ticket-—-short-lived-ticket) | Yes | Exchange your key for a 10-minute ticket | | `GET` | [`/voices`](#get-/voices-—-list-voice-styles), [`/languages`](#get-/languages-—-list-supported-languages), [`/models`](#get-/models-—-list-tts-models), [`/config`](#get-/config-—-server-configuration), [`/status`](#get-/status-—-runtime-status), [`/v1/pricing`](#get-/v1/pricing-—-rate-card), [`/ready`](#get-/ready-—-readiness) | No | Discovery | Authenticated endpoints accept `Authorization: Bearer `, `X-API-Key: ` or `?api_key=`, with an API key or a `wst_` ticket ([Authentication](/authentication)). Streaming synthesis and live transcription run over WebSocket: see [Real-time Streaming](/api-reference/streaming) and [Speech-to-Text](/sdk/stt). Phone numbers and calls are in the [Call Center API](/api-reference/call-center). Errors use the structured shape in the [Error Catalog](/api-reference/errors), except where noted below. *** ## `POST /tts/synthesize` — TTS Synthesis Synthesizes text and returns the whole clip as a WAV file. Billed per character from your balance ([rate card](/api-reference/rate-card): `tts_per_million_chars`). ### Request ```json theme={null} { "text": "Hello, world!", "voice": "F1", "language": "en" } ``` | Parameter | Type | Required | Default | Description | | :- | :- | :- | :- | :- | | `text` | `string` | Yes, unless `segments` is given | — | Text to synthesize. | | `voice` | `string` | Yes | — | Voice slot (`F1`–`F5`, `M1`–`M5`) or one of your `clone_…` ids. Unknown ids answer `400` `validation.invalid_voice`. See [Voices](/voices-languages-models#voices). | | `language` | `string` | No | none | ISO code from `GET /languages`. Unknown codes answer `400` `validation.invalid_language`. Without it, synthesis has no language hint and the slot resolves to the English speaker; pass it for predictable results. | | `segments` | `array` | No | — | Several voices or languages in one clip (below). When present, top-level `text` is ignored, though still counted toward the character limit. | | `steps` | `int` | No | — | `1`–`8`; a higher value is treated as `8`, without an error. Accepted for compatibility; no effect on versa-2.0. | | `cfg` | `number` | No | — | `1`–`4`. Accepted for compatibility; no effect on versa-2.0. | | `cfg_text` | `number` | No | — | `1`–`10`. Accepted for compatibility; no effect on versa-2.0. | | `speed` | `number` | No | `1.0` | A value outside 0.5–2.0 is reset to `1.0`. Accepted for compatibility; no effect on versa-2.0. | | `pronunciation_dictionary_ids` | `string[]` | No | — | Pronunciation dictionaries to apply, on top of your default one. See [Pronunciation](/api-reference/pronunciation). | | `pronunciations` | `array` | No | — | Pronunciation entries for this request only (`{term, say_as: {lang: respelling}}`); they win over every dictionary. A malformed entry answers `400` `validation.invalid_request_format`. | | `temperature` | `number` | No | `0.3` | How varied the delivery is, `0.1`–`1.0`; higher sounds livelier and less predictable. Outside the range answers `400` `validation.invalid_request_format`. | Each entry in `segments` is either speech, `{ "text", "voice"?, "language"? }` (falling back to the top-level `voice` and `language`), or a pause, `{ "pause_ms": 500 }`. Every segment's voice and language are validated before any audio is produced, so a bad value in the last segment fails the request without synthesizing the others. ```json theme={null} { "voice": "F1", "language": "en", "segments": [ { "text": "Welcome to the show." }, { "pause_ms": 400 }, { "text": "Bienvenidos al programa.", "voice": "M2", "language": "es" } ] } ``` The `text` may carry [expression tags](/api-reference/expression-tags) (`[breath]`, `[laugh]`, `[sigh]`, and the emotions `[happy]`, `[sad]`, `[angry]`, `[surprised]`, `[fearful]`, `[disgusted]`, `[excited]`, `[anxious]`) that the voice performs; each sound adds time to the clip. > [!NOTE] > > The older names `voice_id`, `lang` and `quality` are accepted as aliases. `quality` is ignored. New code should use `voice` and `language`. ### Limits | Limit | Value | Over the limit | | :- | :- | :- | | Characters, counted across `text` and every segment | 5,000 | `400` `validation.text_too_long` | | Segments | 200 | `400` `validation.text_too_long` | | `pause_ms` per pause | 0–10,000 | `400` `validation.text_too_long` | | Pauses in total | 60,000 ms | `400` `validation.text_too_long` | | Request body | 1 MB | `400` `validation.invalid_request_format` | Characters are counted as characters, not bytes: an accented letter is one. ### Response `200`, `Content-Type: audio/wav`: 16-bit PCM, 44.1 kHz, mono. | Status | Body | When | | :- | :- | :- | | `400` | Error catalog shape | `validation.invalid_request_format` (bad JSON, missing `text` or `voice`), `validation.invalid_voice`, `validation.invalid_language`, `validation.text_too_long` | | `401` | Error catalog shape | `auth.missing_key`, `auth.invalid_key` | | `402` | Error catalog shape | `billing.insufficient_balance`, `billing.account_disputed`, `billing.limit_reached` ([Billing errors](/api-reference/errors#billing-errors)) | | `503` | `{"error", "voice", "hint"}` with a `Retry-After` header | The synthesis pool is at capacity or not answering. Retry after the number of seconds in `Retry-After`. | The `503` body is not the error-catalog shape: ```json theme={null} { "error": "synthesis capacity reached, retry shortly", "voice": "F1", "hint": "every stream slot on this worker is in use; the request was not malformed" } ``` ### cURL ```bash theme={null} curl -X POST https://api.lokutor.com/tts/synthesize \ -H "Authorization: Bearer $LOKUTOR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"text": "Hello world", "voice": "F1", "language": "en"}' \ --output hello.wav ``` *** ## `POST /stt/transcribe` — Speech-to-Text Transcribes one complete audio clip. For live transcription from a microphone, use `WS /ws/stt` ([Speech-to-Text](/sdk/stt)). Recognition covers English, Spanish, Catalan, Galician, Basque, Portuguese, French, Italian and German, with one model for all nine. The text comes back written out: digits, phone numbers, e-mail addresses, punctuation and casing. Billed per minute of audio ([rate card](/api-reference/rate-card): `stt_per_minute`). ### Request Send either `multipart/form-data` with the file in a field named `audio` (plus optional `language` and `keyterms`), or JSON with base64 audio: ```json theme={null} { "audio": "", "format": "wav", "language": "en" } ``` | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `audio` | `string` | — | Base64 audio (JSON only; use the `audio` form field for multipart) | | `format` | `string` | `"wav"` | `"wav"`, or `"pcm16"` for raw 16-bit little-endian mono samples | | `sample_rate` | `int` | `16000` | Required for `"pcm16"`; read from the header for WAV | | `language` | `string` | detected | One of `en`, `es`, `ca`, `gl`, `eu`, `pt`, `fr`, `it`, `de`. Send it whenever you know it: it makes one-word replies ("sí", "no") reliable and keeps the transcript in that language. Without it the language is detected from the clip. | | `keyterms` | `string[]` or `string` | — | Custom vocabulary: names, brands and terms to write your way when what is heard is close (a list, or one comma-separated string; a form field takes the comma-separated form). Up to 100 terms of 40 characters; more answers `400` `validation.invalid_request_format`. See [Custom vocabulary](/guides/custom-vocabulary). | **Accepted audio:** WAV with 8- or 16-bit PCM, mono or stereo, at 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100 or 48000 Hz, up to 10 MB. Anything else answers `400` `validation.invalid_request_format`. This API's own TTS output (44.1 kHz WAV) is accepted as is. ### Response ```json theme={null} { "text": "Hello, this is a test.", "latency_ms": 240, "engine": "lokutor-stt", "sample_rate": 16000, "language": "en", "duration_seconds": 2.1, "segments": [ { "text": "Hello, this is a test.", "start": 0.0, "end": 2.1, "duration": 2.1 } ] } ``` ### cURL ```bash theme={null} curl -X POST https://api.lokutor.com/stt/transcribe \ -H "Authorization: Bearer $LOKUTOR_API_KEY" \ -F "audio=@recording.wav" \ -F "language=en" ``` *** ## `POST /denoise` — Audio Denoising Removes background noise from a WAV file with Psst, the same model that cleans callers' audio on agent calls. Billed per minute of audio ([rate card](/api-reference/rate-card): `denoise_per_minute`). ### Request `multipart/form-data` with the WAV file in a field named `audio`. The same formats and the same 10 MB limit as `/stt/transcribe` apply; anything else answers `400` `validation.invalid_request_format`. If the denoiser is unavailable or fails, the answer is `503` `agent.provider_error`. ```bash theme={null} curl -X POST https://api.lokutor.com/denoise \ -H "Authorization: Bearer $LOKUTOR_API_KEY" \ -F "audio=@input.wav" \ --output clean.wav ``` ### Response `200`, `Content-Type: audio/wav`: the denoised audio, 16-bit PCM. *** ## `POST /ws-ticket` — Short-lived Ticket Exchanges your API key, sent in the `Authorization` or `X-API-Key` header (never the URL), for a ticket that works anywhere a key does for 10 minutes. Use it to keep the key out of browsers. See [Authentication](/authentication#short-lived-tickets) and [Secure browser setup](/guides/secure-browser-setup). ```bash theme={null} curl -X POST https://api.lokutor.com/ws-ticket -H "Authorization: Bearer $LOKUTOR_API_KEY" ``` ```json theme={null} { "ticket": "wst_…", "expires_in": 600 } ``` *** ## Discovery These endpoints need no key. ### `GET /voices` — List Voice Styles ```json theme={null} { "model": "versa-2.0", "voices": [ { "id": "F1", "name": "Claire", "gender": "female", "languages": ["en", "es", "ca", "gl", "eu", "pt", "fr", "it", "de"] }, { "id": "M1", "name": "James", "gender": "male", "languages": ["en", "es", "ca", "gl", "eu", "pt", "fr", "it", "de"] } ] } ``` | Field | Type | Description | | :- | :- | :- | | `model` | `string` | The synthesis model serving these voices | | `voices[].id` | `string` | Voice slot, e.g. `F1`, `M3` | | `voices[].name` | `string` | The slot's display name. The speaker heard depends on `language`: each language has its own speaker in each slot ([Voices](/voices-languages-models#voices)). | | `voices[].gender` | `string` | `"female"` or `"male"` | | `voices[].languages` | `string[]` | Languages the slot can speak: all thirteen | `GET /voices` lists the built-in slots only. Your cloned voices are listed in the dashboard under **Voices**, each with its `clone_…` id; any endpoint that takes a `voice` accepts one only from an API key on the account that created it, and answers `validation.invalid_voice` from any other account. ### `GET /languages` — List Supported Languages Every language text-to-speech can speak. Speech recognition covers nine of them (not `nl`, `pl`, `ro`, `ru`). ```json theme={null} { "languages": [ { "code": "en", "name": "English" }, { "code": "es", "name": "Spanish" }, { "code": "ca", "name": "Catalan" }, { "code": "gl", "name": "Galician" }, { "code": "eu", "name": "Basque" }, { "code": "pt", "name": "Portuguese" }, { "code": "fr", "name": "French" }, { "code": "it", "name": "Italian" }, { "code": "de", "name": "German" }, { "code": "nl", "name": "Dutch" }, { "code": "pl", "name": "Polish" }, { "code": "ro", "name": "Romanian" }, { "code": "ru", "name": "Russian" } ] } ``` ### `GET /models` — List TTS Models ```json theme={null} { "models": [ { "name": "versa-2.0", "description": "Primary production model", "default": true } ] } ``` `versa-2.0` is the only model served. ### `GET /config` — Server Configuration ```json theme={null} { "max_text_length": 5000, "min_speed": 0.5, "max_speed": 2.0, "min_steps": 1, "max_steps": 8, "sample_rate": 44100, "channels": 1 } ``` | Field | Description | | :- | :- | | `max_text_length` | Maximum characters per synthesis request | | `min_speed`, `max_speed` | The range `/ws/tts` accepts for `speed` without an error | | `min_steps`, `max_steps` | The highest `steps` synthesis honours: `POST /tts/synthesize` treats anything above `8` as `8` (`/ws/tts` still accepts up to `128` without an error). Neither parameter changes the audio on `versa-2.0` ([Parameters](/voices-languages-models#parameters)). | | `sample_rate`, `channels` | Output audio format: 44,100 Hz, mono | ### `GET /status` — Runtime Status ```json theme={null} { "status": "ok", "timestamp": "2026-10-18T16:31:23.955Z", "version": "1.1.0", "runtime": "go1.24.10", "inference": "cpu", "uptime_seconds": 17, "goroutines": 61, "mem_alloc_bytes": 73432552, "active_connections": 0, "failed_requests": 0, "ready": true } ``` `status` is `"ok"` or `"warming_up"`, and `ready` says whether the server can serve. The other fields describe the one API server that answered and are informational; `inference` is an internal label and does not say where synthesis runs. ### `GET /v1/pricing` — Rate Card Every price Lokutor charges, as JSON. Fields and an example are on the [Rate Card](/api-reference/rate-card) page; how the prices apply is in [Pricing and billing](/pricing). ### `GET /ready` — Readiness `200` `{"ready": true, "status": "ready"}` once the server can serve requests; `503` `{"ready": false, "status": "not_ready"}` while it is starting. Use it for uptime checks. *** ## JavaScript SDK The SDK wraps the discovery endpoints as static methods on `VoiceAgentClient`. They call `https://api.lokutor.com` and throw `LokutorError` on failure. ```typescript theme={null} import { VoiceAgentClient } from '@lokutor/sdk'; const voices = await VoiceAgentClient.fetchVoices(); // GET /voices const languages = await VoiceAgentClient.fetchLanguages(); // GET /languages const models = await VoiceAgentClient.fetchModels(); // GET /models const config = await VoiceAgentClient.fetchConfig(); // GET /config const status = await VoiceAgentClient.fetchStatus(); // GET /status const ready = await VoiceAgentClient.fetchHealth(); // GET /ready ``` *** ## cURL Examples ```bash theme={null} curl -s https://api.lokutor.com/ready curl -s https://api.lokutor.com/voices curl -s https://api.lokutor.com/languages curl -s https://api.lokutor.com/config curl -s https://api.lokutor.com/v1/pricing ``` *** ## Related Pages * [Real-time Streaming](/api-reference/streaming): TTS over WebSocket * [Voice Chat](/api-reference/voice-chat) and [WebSocket Protocol](/guides/websocket-protocol): the voice agent * [Error Catalog](/api-reference/errors) * [OpenAPI Spec](/api-reference/openapi-spec) # Speech to text with speaker diarization Source: https://docs.lokutor.com/api-reference/speech-to-text Transcribe a recording and label who said each word. ElevenLabs Scribe-compatible. `POST https://api.lokutor.com/v1/speech-to-text` transcribes a recording and, when you ask for it, says which speaker said each word. The request and response follow the ElevenLabs Speech to Text (Scribe) shape, so a client written for that API works by changing the base URL and the key. ## What it is, honestly Diarization splits a recording into speakers and numbers them `speaker_0`, `speaker_1`, ... in order of first appearance. * **Where it works well:** English meetings. On a real 60-minute, 5-person meeting from the AMI corpus it measured a diarization error rate of 8.0%, found 5 of 5 speakers, and attributed 99.4% of words to the right speaker. * **Where it does not:** very short interjections ("yeah", "mm") and overlapping speech are missed or given to the wrong speaker. * **Not yet measured:** telephone-quality audio and non-English audio. Treat the speaker labels there as unverified. Transcription itself is the same recogniser as `/stt/transcribe`, with greedy decoding (not the language-model beam). ## Request `multipart/form-data`. Authenticate with `xi-api-key: YOUR_KEY`, `X-API-Key: YOUR_KEY` or `Authorization: Bearer YOUR_KEY`. ```bash theme={null} curl https://api.lokutor.com/v1/speech-to-text \ -H "xi-api-key: $LOKUTOR_API_KEY" \ -F file=@meeting.wav \ -F language_code=eng \ -F diarize=true \ -F num_speakers=5 \ -F timestamps_granularity=word ``` | Field | Type | Default | Description | | - | - | - | - | | `file` | file | required | WAV, PCM 8 or 16 bit, mono or stereo (stereo is mixed to mono), 8 to 48 kHz. Other formats (MP3, M4A, ...) are not decoded yet: convert first. | | `model_id` | string | | Accepted and ignored. | | `language_code` | string | detect | ISO-639-1 or ISO-639-3: `ca`/`cat`, `de`/`deu`, `en`/`eng`, `es`/`spa`, `eu`/`eus`, `fr`/`fra`, `gl`/`glg`, `it`/`ita`, `pt`/`por`. Any other language is refused with 400. | | `diarize` | boolean | `false` | Label each word with its speaker. | | `num_speakers` | integer 1-32 | detect | The number of speakers, if you know it. Improves the result when given. | | `timestamps_granularity` | `none`, `word`, `character` | `word` | `character` behaves as `word`. With `none`, `words` is empty, unless `diarize` is true (the speakers are returned per word regardless). | | `tag_audio_events` | boolean | | Accepted and ignored: no audio events are produced. | ## Response ```json theme={null} { "language_code": "eng", "language_probability": 1.0, "text": "Hello everyone. Thanks for joining.", "words": [ {"text": "hello", "start": 0.12, "end": 0.40, "type": "word", "speaker_id": "speaker_0"}, {"text": " ", "start": 0.40, "end": 0.56, "type": "spacing", "speaker_id": "speaker_0"}, {"text": "everyone", "start": 0.56, "end": 0.92, "type": "word", "speaker_id": "speaker_0"}, {"text": "thanks", "start": 2.10, "end": 2.34, "type": "word", "speaker_id": "speaker_1"} ] } ``` * `language_code`: ISO-639-3 (`eng`, `spa`, ...). `language_probability` is `1.0` when you passed `language_code` and `null` when the language was detected. * `text`: the full transcript, formatted. * `words[].type`: `word`, or `spacing` for the gap between words. * `words[].speaker_id`: `speaker_0` for everything when `diarize` is false. ## Errors Errors use the ElevenLabs shape, with the HTTP status you would expect: ```json theme={null} {"detail": {"status": "audio_too_long", "message": "Diarization takes recordings up to 7200 seconds; this one is 7510."}} ``` | HTTP | `status` | When | | - | - | - | | 400 | `invalid_parameters` | `diarize`, `num_speakers` or `timestamps_granularity` is not valid. | | 400 | `unsupported_language` | `language_code` is not one of the nine languages. | | 400 | `unsupported_audio` | The file is not a readable WAV or its sample rate is not supported. | | 400 | `audio_too_long` | A diarization request longer than the limit (7,200 s, 2 hours). | | 400 | `invalid_request` | No `file`, an empty file, or the recogniser refused the request. | | 401 | `invalid_api_key` | Missing or invalid key. | | 402 | `quota_exceeded` | Your balance or plan limit does not cover the request. | | 403 | `diarization_not_available` | Diarization is not enabled yet. | | 413 | `file_too_large` | Over 10 MB, or over 256 MB for a diarization request. | | 429 | `too_many_concurrent_requests` | Your account already has a diarization request running. | | 503 | `diarization_busy` | The diarization service could not be started within 5 minutes. Nothing is billed. Wait a few minutes (the `Retry-After` header says 120 s) and send it again. | | 502 | `transcription_failed` | The recogniser could not process the audio. Retry. | ## Limits * Audio length for `diarize=true`: 7,200 seconds (2 hours). * File size: 10 MB without diarization; 256 MB with it. Two hours of 16 kHz mono WAV is 219 MB; stereo or 44.1 kHz audio of that length is larger than the limit, so send 16 kHz mono (or cut the file). * One diarization request at a time per account. Without diarization the usual concurrency rules apply. * **Speaker labels run on a CPU service, so they are not real time.** If no diarization has run in the last 10 minutes, the first request waits about a minute while the service starts; requests that follow within 10 minutes start at once. Processing takes about 11 minutes for an hour of audio, so a two-hour file takes about 22 minutes. Keep the connection open and set your client timeout to at least 45 minutes. There is no polling endpoint: the answer arrives on the same connection. ## Pricing Transcription is billed per audio minute at the speech-to-text rate. Speaker labels are a separate line on top: `stt_diarization_per_minute` per audio minute (on the rate card, `GET /v1/pricing`). At the current card that is $0.0017 per audio minute ($0.10 per hour, $0.20 for a two-hour file), with no minimum: a short file costs its length. Together with transcription ($0.0014 per minute) a diarized minute is \$0.0031. A request that fails, or is answered 503 `diarization_busy`, is not billed. ## Differences from ElevenLabs * `words[].text` is spoken-form (lower case, no punctuation); the top-level `text` is formatted. * No `logprob` fields. * No `audio_event` entries; `tag_audio_events` is ignored. * `language_probability` is `1.0` when `language_code` is given and `null` when detected (ElevenLabs returns an estimated probability). * A word's `end` is the frame its last piece was emitted at, so words are short and `spacing` entries carry the gaps between them. * Speakers are numbered by first appearance (`speaker_0` is whoever speaks first). * Languages: `ca de en es eu fr gl it pt` only. * WAV input only for now. * Greedy decoding, not the language-model beam. * Not implemented: `webhook`, `cloud_storage_url`, `additional_formats`, `entity_detection`, `keyterms` on this route. ## Also on `/stt/transcribe` `POST /v1/stt/transcribe` accepts `diarize` and `num_speakers` too, and returns Lokutor's own shape: the usual fields plus `turns` (consecutive speech by one speaker) and `segments`, exactly as the recogniser produces them. Same limits and errors (in Lokutor's error shape). ## Attribution Speaker diarization uses [pyannote speaker-diarization-community-1](https://huggingface.co/pyannote/speaker-diarization-community-1) (pyannote.audio), licensed under CC-BY-4.0. See [Licences](/licences) for the full notice. # Real-time Streaming Source: https://docs.lokutor.com/api-reference/streaming Text-to-speech over WebSocket (wss://api.lokutor.com/ws/tts): request fields, default voices, the 5,000-character limit, binary PCM responses, EOS, error frames, billing and concurrency behaviour ## Connection ``` wss://api.lokutor.com/ws/tts ``` `/ws/tts` and `/ws` are the same endpoint. Authenticate the handshake with an `Authorization: Bearer` or `X-API-Key` header, or with `?api_key=` where headers cannot be set (the browser `WebSocket`). In a browser, pass a short-lived `wst_` ticket rather than your key ([Authentication](/authentication)). The socket stays open: send as many requests as you like, one after another, and each is a separate synthesis. ## Request ```json theme={null} { "text": "Hello, how can I help you today?", "voice": "M1", "language": "en" } ``` | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `text` | string | — | Text to synthesize. At most 5,000 characters (counted as characters, not bytes). | | `voice` | string | see below | Voice slot (`F1`–`F5`, `M1`–`M5`) or one of your `clone_…` ids. See [Voices](/voices-languages-models#voices). | | `language` | string | none | ISO code from `GET /languages`. Pass it explicitly: it chooses the speaker behind the voice slot as well as the pronunciation. | | `speed` | number | — | Must be 0.5–2.0, otherwise an error frame `validation.speed_out_of_range`. Accepted for compatibility; no effect on versa-2.0. | | `steps` | int | — | Must be at most 128, otherwise an error frame `validation.steps_out_of_range`. Accepted for compatibility; no effect on versa-2.0. | | `visemes` | bool | `false` | Lip-sync data. **Not available on the current model**: nothing is sent ([Visemes](/sdk/visemes)). | | `version` | string | — | Accepted and ignored. `versa-2.0` is the only model. | | `pronunciation_dictionary_ids` | string\[] | — | Pronunciation dictionaries to apply, on top of your default one. See [Pronunciation](/api-reference/pronunciation). | | `pronunciations` | array | — | Pronunciation entries for this request only; they win over every dictionary. A malformed entry is an error frame `validation.invalid_request_format`. | | `temperature` | number | `0.3` | How varied the delivery is, `0.1`–`1.0`. Outside the range is an error frame `validation.invalid_request_format`. | The older `lang` name is accepted as an alias for `language`. The `text` may carry [expression tags](/api-reference/expression-tags) (`[breath]`, `[laugh]`, `[sigh]`, and the emotions `[happy]`, `[sad]`, `[angry]`, `[surprised]`, `[fearful]`, `[disgusted]`, `[excited]`, `[anxious]`) that the voice performs; each sound adds time to the audio. **Default voice.** When `voice` is omitted, the server uses `M5` (Noah) for English, `F3` (Emma) for Spanish, and otherwise the language's first voice. Pass a voice explicitly for a stable result. The SDKs' `TTSClient` always sends one (`F1` unless you choose another). ## Response | Frame | Meaning | | :- | :- | | Binary | Int16 PCM audio, 44.1 kHz, mono, little-endian. Large chunks are split into frames of at most 512 KB. | | Text `EOS` | This request is complete. The socket stays open for the next one. | | Text JSON `{"type": "error", "data": {"code", "message", "detail", "retryable"}}` | The request failed; `data` has the [Error Catalog](/api-reference/errors) shape. A validation error is not followed by `EOS`; a synthesis failure (`tts.synthesis_failed`) is. | No other JSON messages are sent: there are no timing or progress frames. ## Errors and billing * A message that fails validation (empty or too-long `text`, an unknown `voice` or `language`, `speed` or `steps` out of range) gets an error frame and is **not billed**. * A message whose synthesis fails on Lokutor's side gets an error frame and is not billed either. * Successful messages are billed per character ([rate card](/api-reference/rate-card): `tts_per_million_chars`). * A balance below the minimum refuses the handshake with `402` ([Billing errors](/api-reference/errors#billing-errors)). ## Concurrency Each open `/ws/tts` socket counts toward your account's concurrent sessions (3 before the first top-up, 10 after; [Limits](/pricing#limits)). Past that limit the socket **opens**, sends an `auth.rate_limited` error frame, and closes. This differs from `/ws/agent` and `/ws/stt`, which refuse the handshake with `429`. Close sockets you are not using. ## Example (Node.js 22+) ```javascript theme={null} // save as stream.mjs and run: node stream.mjs const key = encodeURIComponent(process.env.LOKUTOR_API_KEY); const ws = new WebSocket(`wss://api.lokutor.com/ws/tts?api_key=${key}`); ws.binaryType = 'arraybuffer'; let bytes = 0; ws.onopen = () => ws.send(JSON.stringify({ text: 'Hello from Lokutor.', voice: 'F1', language: 'en' })); ws.onmessage = (event) => { if (event.data instanceof ArrayBuffer) { bytes += event.data.byteLength; // play or store the PCM here } else if (event.data === 'EOS') { console.log(`done: ${bytes} bytes of audio`); ws.close(); } else { console.error(JSON.parse(event.data)); // error frame ws.close(); } }; ``` ## Best practices * Reuse one socket for several requests to avoid a new handshake each time. * Start playback on the first binary frame; do not wait for `EOS`. * Pass `voice` and `language` on every request. * All [nine languages](/voices-languages-models#languages) are available. # Voice Chat (Conversational AI) Source: https://docs.lokutor.com/api-reference/voice-chat Quick reference for wss://api.lokutor.com/ws/agent: query parameters (agent_id, nfe, cfg, disable_external_tools, caller_phone), configuration messages, server events, barge-in, silence and idle timeouts For the full wire-protocol reference (message-by-message), see [WebSocket Protocol](/guides/websocket-protocol). This page is the quick-reference version. ## Audio specs | Property | Input | Output | | :- | :- | :- | | Sample Rate | 16 kHz | 44.1 kHz | | Format | Int16 PCM | Int16 PCM | | Channels | 1 (mono) | 1 (mono) | Agent audio always arrives as a base64-encoded `audio` JSON message — this endpoint never sends raw binary audio frames to the client (unlike `/ws/tts`). ## Connection ``` wss://api.lokutor.com/ws/agent?agent_id=your-agent-id ``` Authenticate the handshake with an `Authorization: Bearer` or `X-API-Key` header, or with `?api_key=` where headers cannot be set. In a browser, pass a short-lived `wst_` ticket, never your key ([Authentication](/authentication)). The handshake is refused with `401` for a bad credential, `402` (plain text) when the balance cannot start a session, `404` `agent.not_found` for an `agent_id` that is not yours, and `429` `auth.rate_limited` past your account's concurrent sessions. Optional query parameters: | Parameter | What it does | | - | - | | `agent_id` | Runs one of your dashboard agents: its prompt, voice, tools, knowledge base and integrations. The `voice`, `language` and `prompt` messages you send after connecting override the agent's own for this session. | | `caller_phone`, `caller_email` | Who the caller is, for an agent with your CRM switched on: the agent looks them up when the call starts and logs the call on their record ([Tool Calling → Your CRM](/sdk/tool-calling#your-crm-opt-in)). Phone numbers in international form, e.g. `%2B34612345678`. | | `disable_external_tools=1` | Leaves out the agent's tools that call your URLs (webhook tools) for this session. Built-in tools stay. | | `nfe` | Denoising steps for this session. Live sessions can only lower it: values are clamped to 1–6, and the default is the maximum. Accepted for compatibility; no effect on versa-2.0. | | `cfg` | Voice guidance, clamped to 1–4. Accepted for compatibility; no effect on versa-2.0. | | `cfg_text` | Text guidance. Fixed at 1 on live sessions. Accepted for compatibility; no effect on versa-2.0. | Query values override the same keys in the agent's config. ## Agent config A session with an `agent_id` runs with that agent's config, set in the dashboard. Keys documented elsewhere: `web_search`, `google_calendar` and the calendar settings, `crm` and `timezone` in [Tool Calling](/sdk/tool-calling#built-in-tools). This one changes how the agent takes its turn: | Key | Type | Default | What it does | | :- | :- | :- | :- | | `speculative_llm` | `boolean` | `true` | **Speculative replies.** The agent starts its reply while the caller pauses, so turns it lands in are answered in about 306 ms instead of about 660 ms. Replies started this way and not used are billed as language-model tokens, about a third of a cent a minute at a typical prompt ([Pricing and billing](/pricing#speculative-replies)). With `false`, the agent asks the model only once the caller's turn has ended: no unused replies to pay for, and replies about 255 ms slower on average. | ## Initialization Send configuration as JSON messages after connecting, in this order: ```json theme={null} { "type": "voice", "data": "F1" } { "type": "language", "data": "en" } { "type": "tools", "data": [{ "type": "function", "function": { "name": "get_weather" } }] } { "type": "visemes", "data": false } { "type": "prompt", "data": "You are a helpful assistant." } { "type": "rates", "playback": 44100, "input": 16000 } ``` Send `rates` last: receiving it tells the server your configuration is complete and releases the first conversational turn. Each of `voice`/`language`/`prompt`/`rates` is acknowledged with a `status` message (`voice_set`, `language_set`, `prompt_set`, `rates_set`). With an `agent_id`, every message except `rates` is optional: send only what you want to override. Without one, send at least `prompt`. An unknown voice or language is answered with an error frame, `{"type": "error", "data": {"code": "validation.invalid_voice", …}}` (or `validation.invalid_language`), and **no** `voice_set` / `language_set` ack; the session keeps its previous value. **Language.** A `language` (or the agent's own) is kept for the whole session: the agent speaks it, and speech recognition listens for it, short replies included. Send an empty string, `{"type": "language", "data": ""}`, to let the agent follow the caller instead. It recognises the caller's language from what they say and replies in it in the same voice. A short reply such as "yes" or a number is heard in the language the caller last spoke, and the agent switches when the caller does. With neither an `agent_id` nor a `language` message, the agent speaks English and recognition follows the caller. ## Client to server Send microphone audio as binary Int16 PCM frames (16 kHz, mono, \~20ms chunks). You can also send the same audio as `{"type":"audio","data":""}` if binary frames aren't convenient in your environment. Other client → server messages: `pitch` (adjust pitch-shift), `reset` (clear conversation context), `tool_result` (return a client-executed tool's result — see [Tool Calling](/sdk/tool-calling)). ## Server to client | Event | Data | When | | :- | :- | :- | | `status` | `listening`, `thinking`, `speaking`, `interrupted`, `connected`, or a `*_set`/`reset` ack | State changes and config acks | | `transcript` | `{ role, data, partial? }` | Speech transcription (user or agent) | | `transcript_truncated` | `{ role: "agent", data, full, emitted }` | The user cut the agent off. `data` is what they actually heard, ending in `…` where they stopped hearing it (empty if they heard nothing). If `emitted` is true, replace the agent `transcript` whose text was `full`; otherwise add `data` as a new agent line | | `transcript_revised` | `{ role: "user", data, previous }` | The user paused mid-sentence, the agent barely started, and the user carried on: both halves were transcribed together. Replace the last user line (`previous`) with `data` and drop any agent line after it. Sent instead of a `transcript` for the continuation | | `audio` | Base64-encoded PCM chunk + `generation` | Agent speaking | | `visemes` | Array of `{ v, c, t }` | Lip-sync data | | `tool_call` | `{ name, arguments, call_id }` | Tool execution | | `server_rates` | `{ playback, input }` | Sent on connect and in response to a client `rates` message | | `error` | A structured error object (`code`, `message`, `detail`, `retryable`) or a plain string | Configuration and pipeline errors. Invalid voice or language arrive structured; runtime pipeline errors may be a string. Handle both. | ## Barge-in When the user starts speaking over the agent, the server sends `status: listening` and stops sending new audio for the reply, but the barge-in is only tentative: keep playing what you already have. `status: interrupted` follows once the interruption is real (the user kept talking for 400 ms, or their utterance is confirmed as speech rather than noise, a backchannel or an echo of the agent); stop playback and clear queued audio then. If it was a false alarm, the server sends `status: speaking` (or `thinking`, if the reply was still being generated) and the reply continues under the same `generation`. See [Handling Interruptions](/guides/handling-barge-in). An agent reply is sent as a `transcript` as soon as it is generated, which is before it has finished playing. When the user interrupts, a `transcript_truncated` follows with what they actually heard, and the agent's own memory of the conversation is corrected the same way. If the user was only pausing and the agent had said no more than a word or two, the user's two fragments become one turn (`transcript_revised`) and the agent answers the whole sentence. A reply the user never heard any of — they started speaking again before it began to play — is not kept. It is either never sent as a `transcript`, or, if it already was, withdrawn with a `transcript_truncated` whose `data` is empty and `emitted` true. The agent forgets it too, and answers what the user goes on to say. ## Silence If the user says nothing for 10 seconds after the agent finishes speaking, the agent speaks once, unprompted: it asks whether they are still there or need anything else — or, if their last turn went unanswered, answers it. It arrives like any other reply (`transcript`, then `audio` under a new `generation`), at most once per silence; the next time the user speaks re-arms it. It never acts on the user's behalf: no tool is called while they are silent, even if the agent's last line offered to do something. ## Idle sessions A session in which nobody has spoken for 5 minutes ends: the agent says goodbye (as an ordinary `transcript` and `audio`), and the socket closes with code `1000` and the reason `nobody has spoken for 5 minutes`. A session whose account balance runs out closes with `1008` and the reason `account balance exhausted`. ## Related Pages * [WebSocket Protocol](/guides/websocket-protocol) — full message reference * [Handling Interruptions](/guides/handling-barge-in) — barge-in mechanism in detail * [Tool Calling](/sdk/tool-calling) — `tool_call` / `tool_result` flow and built-in tools # Authentication Source: https://docs.lokutor.com/authentication API keys, the three ways to send one (Authorization: Bearer, X-API-Key, ?api_key=), and short-lived wst_ tickets from POST /ws-ticket for browsers All requests to the Lokutor API must be authenticated with an API key. ## Getting an API key 1. Sign up at [app.lokutor.com](https://app.lokutor.com) 2. Go to **API Keys** in the dashboard 3. Click **Create API Key** and give it a name Your key will look like `sk_...`. **It is shown once, when you create it**: copy it then and store it securely. Lokutor keeps only a hash of it, so neither the dashboard nor support can show it again; the dashboard lists each key by its first and last characters (`sk_live…a1b2`). If you lose a key, delete it and create a new one. ### Billing and limits Every key on an account spends the same prepaid balance. Sessions and requests are charged as you use them (a voice agent is 4.2¢ a minute plus the language model by the token, about 5.2¢ a typical minute), and a new session or request needs at least \$0.25 of balance. An account can hold 3 sessions at a time before its first top-up and 10 after; higher on request. Rates, top-ups, the welcome credit and the `402` errors are in [Pricing and billing](/pricing). ## Using your API key **Environment variable (recommended):** ```bash theme={null} export LOKUTOR_API_KEY=sk_your_key_here ``` Every authenticated endpoint (REST, every WebSocket, and `/callcenter/*`) accepts the credential in any of three forms: | Form | Example | | :- | :- | | `Authorization` header | `Authorization: Bearer sk_your_key_here` | | `X-API-Key` header | `X-API-Key: sk_your_key_here` | | `api_key` query parameter | `wss://api.lokutor.com/ws/agent?api_key=sk_your_key_here` | Prefer a header: it keeps the credential out of URLs, which can be recorded in logs and traces. Use the query parameter only where a client cannot set headers, such as the browser `WebSocket` and `EventSource` APIs, and there pass a ticket rather than the key. ### Short-lived tickets `POST /ws-ticket` exchanges your API key for a ticket that starts with `wst_` and works for 10 minutes. A ticket is accepted anywhere a key is (in any of the three forms above) and can be reused until it expires. It reveals nothing about the key, so one that ends up in a browser console or a log is useless soon after. ```bash theme={null} curl -X POST https://api.lokutor.com/ws-ticket -H "Authorization: Bearer $LOKUTOR_API_KEY" # {"ticket":"wst_…","expires_in":600} ``` ``` wss://api.lokutor.com/ws/agent?api_key=wst_… ``` The exchange itself takes the key only in the `Authorization` or `X-API-Key` header, never in the URL, and a ticket cannot be exchanged for another ticket. In a browser, mint tickets on your backend so the long-lived key never reaches the page; the JavaScript SDK's `auth` option fetches a fresh one before every connection. See [Secure browser setup](/guides/secure-browser-setup). ## Security * Never commit API keys to version control * Never put an API key in browser or mobile app code: use tickets * Use separate keys for development, staging, and production * Rotate keys regularly * If a key is compromised, delete it from the dashboard and create a new one ## Multiple environments Create separate keys for each environment so you can monitor usage independently and revoke keys without affecting other systems. # Benchmarks Source: https://docs.lokutor.com/benchmarks Measured accuracy of Lokutor Conv 2.0 (speech to text) and Versa 2.0 (text to speech) on public test sets, with the method, so anyone can reproduce it. Every number here is a measurement we ran ourselves through the public API (`api.lokutor.com`), on public test sets, on 3 and 4 November 2026. Raw per-utterance outputs and the scripts are kept; ask us for them. We show the weak results next to the strong ones. ## Speech to text: Conv 2.0 Word error rate (WER, lower is better) with the [Open ASR Leaderboard](https://github.com/huggingface/open_asr_leaderboard) code and normaliser, through `POST /v1/speech-to-text` (ElevenLabs-compatible). Our submission to the leaderboard is [pull request #267](https://github.com/huggingface/open_asr_leaderboard/pull/267). **English, short-form** | Test set | WER % | | :- | -: | | LibriSpeech test-clean | 2.84 | | SPGISpeech | 3.99 | | VoxPopuli | 4.11 | | Monsoon (en-IN) | 5.83 | | URGENT 2024 (clean) | 6.33 | | LibriSpeech test-other | 6.69 | | GigaSpeech | 8.97 | | AMI | 9.48 | | Earnings22 | 10.81 | | URGENT 2024 (noisy) | 15.34 | The Open ASR average over its nine standard sets (URGENT clean excluded) is **7.56%**; over the seven classic sets (AMI, Earnings22, GigaSpeech, both LibriSpeech sets, SPGISpeech, VoxPopuli) it is 6.70%. Throughput as the leaderboard defines RTFx: 13.6 on average, measured per request over the internet with 8 requests in flight, so it is a per-request figure, not server capacity. **Other languages** | Language | FLEURS | Common Voice (5,000-clip sample) | MLS | | :- | -: | -: | -: | | Spanish | 6.14 | 8.76 | 5.65 | | Italian | 6.94 | 8.84 | 9.47 | | German | 9.00 | 9.11 | n/a | | Portuguese | 9.22 | 4.73 | 12.00 | | French | 10.45 | 11.73 | 7.23 | **Basque and Spanish** ([HiTZ test sets](https://huggingface.co/datasets/HiTZ/benchmark_eseu_testsets), Whisper basic normaliser, so comparable with HiTZ's model cards): Basque **10.1%** (4.4 h; Common Voice 8.3, parliament 6.4, OpenSLR 21.7) and Spanish **9.0%** (7.5 h; parliament 5.0, MLS 6.5, VoxPopuli 10.0, Common Voice 11.4, OpenSLR 13.5). Details that matter: Common Voice rows are random 5,000-clip samples (seed 42) of the full test sets; three Gigaspeech and 34 AMI predictions came back empty and are counted as deletions; the model writes numerals where some references spell numbers out. ## Text to speech: Versa 2.0 **Seed-TTS-Eval, English** (1,088 Common Voice utterances, WER only, Whisper-large-v3 as the recogniser): **1.82%** with voice F1 and **1.90%** with voice M1. We report WER only: the benchmark's speaker-similarity score compares the output to a prompt speaker, and our stock voices are not conditioned on that clip, so the number would not mean anything. This is also not the benchmark's zero-shot cloning task. The scoring path was re-implemented for English (the official script needs CUDA); normalisation follows the repository's `run_wer.py`. **Speed and capacity** are measured separately and published in the [models page](https://lokutor.com/models): about 90 ms to first audio under load. # Getting Started Source: https://docs.lokutor.com/getting-started Get an API key and synthesize your first audio: one curl request to POST /tts/synthesize, or the JavaScript and Python SDKs, or a raw WebSocket ## Step 1: Get an API key Sign up at [app.lokutor.com](https://app.lokutor.com) and create an API key from the dashboard. Usage is paid from a prepaid balance, and a new account gets \$5 of credit once its email is confirmed: enough for about 95 minutes of conversation with an agent. See [Pricing and billing](/pricing). ```bash theme={null} export LOKUTOR_API_KEY=sk_your_key_here ``` ## Step 2: Synthesize audio > [tab] cURL (no install) > > One request returns a WAV file (16-bit PCM, 44.1 kHz, mono): > > ```bash theme={null} > curl -X POST https://api.lokutor.com/tts/synthesize \ > -H "Authorization: Bearer $LOKUTOR_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{"text": "Hello from Lokutor.", "voice": "F1", "language": "en"}' \ > --output hello.wav > ``` > > `voice` is required on this endpoint. The request fields are described in the [REST API reference](/api-reference/rest#post-/tts/synthesize-—-tts-synthesis). > [tab] Node.js (SDK) > > Requires Node.js 22 or later (the SDK uses the global `WebSocket`). > > ```bash theme={null} > npm install @lokutor/sdk > ``` > > ```typescript theme={null} > // save as tts.mjs and run: node tts.mjs > import { TTSClient, VoiceStyle, Language } from '@lokutor/sdk'; > import fs from 'node:fs'; > > const client = new TTSClient({ apiKey: process.env.LOKUTOR_API_KEY }); > const chunks = []; > > // Resolves when the server has sent all the audio; rejects with a LokutorError on failure. > await client.synthesize({ > text: 'Hello from Lokutor.', > voice: VoiceStyle.F1, > language: Language.ENGLISH, > onAudio: (data) => chunks.push(Buffer.from(data)), > }); > > fs.writeFileSync('output.raw', Buffer.concat(chunks)); > console.log('Saved output.raw'); > // Convert: ffmpeg -f s16le -ar 44100 -ac 1 -i output.raw output.wav > ``` > [tab] Browser (SDK) > > Never put your API key in browser code. Your backend exchanges it for a short-lived ticket, and the page uses the ticket. The backend route is shown in [Secure browser setup](/guides/secure-browser-setup). > > ```typescript theme={null} > import { TTSClient, VoiceStyle, Language } from '@lokutor/sdk'; > > // Your backend calls POST https://api.lokutor.com/ws-ticket with your key and returns { ticket }. > const { ticket } = await fetch('/api/lokutor-ticket', { method: 'POST' }).then((r) => r.json()); > > const audioCtx = new AudioContext(); // create it inside a click handler > let nextTime = audioCtx.currentTime; > > const client = new TTSClient({ apiKey: ticket }); > > await client.synthesize({ > text: 'Hello from Lokutor.', > voice: VoiceStyle.F1, > language: Language.ENGLISH, > onAudio: (pcm16) => { > const int16 = new Int16Array(pcm16.buffer, pcm16.byteOffset, pcm16.byteLength / 2); > const float32 = new Float32Array(int16.length); > for (let i = 0; i < int16.length; i++) float32[i] = int16[i] / 32768; > > const buffer = audioCtx.createBuffer(1, float32.length, 44100); > buffer.getChannelData(0).set(float32); > > const source = audioCtx.createBufferSource(); > source.buffer = buffer; > source.connect(audioCtx.destination); > const start = Math.max(audioCtx.currentTime, nextTime); > source.start(start); > nextTime = start + buffer.duration; > }, > }); > ``` > [tab] Python (SDK) > > Requires Python 3.8 or later. > > ```bash theme={null} > pip install lokutor > ``` > > ```python theme={null} > import os > import wave > from lokutor import TTSClient, VoiceStyle, Language > > client = TTSClient(api_key=os.environ["LOKUTOR_API_KEY"]) > chunks = [] > > client.synthesize( > text="Hello from Lokutor.", > voice=VoiceStyle.F1, > language=Language.ENGLISH, > on_audio=chunks.append, > play=False, # True plays through your speakers: needs pip install "lokutor[audio]" > block=True, > ) > > with wave.open("hello.wav", "wb") as f: > f.setnchannels(1) > f.setsampwidth(2) > f.setframerate(44100) > f.writeframes(b"".join(chunks)) > ``` > [tab] Raw WebSocket (Node.js 22+) > > Node's global `WebSocket` cannot set request headers, so this passes the key as `?api_key=`. To send it in an `X-API-Key` header instead, use the [`ws`](https://www.npmjs.com/package/ws) package (`new WebSocket(url, { headers: { 'X-API-Key': key } })`). > > ```javascript theme={null} > // save as raw-tts.mjs and run: node raw-tts.mjs > import fs from 'node:fs'; > > const key = encodeURIComponent(process.env.LOKUTOR_API_KEY); > const ws = new WebSocket(`wss://api.lokutor.com/ws/tts?api_key=${key}`); > ws.binaryType = 'arraybuffer'; > const chunks = []; > > ws.onopen = () => { > ws.send(JSON.stringify({ text: 'Hello from Lokutor.', voice: 'F1', language: 'en' })); > }; > ws.onmessage = (event) => { > if (event.data instanceof ArrayBuffer) { > chunks.push(Buffer.from(event.data)); // Int16 PCM, 44.1 kHz, mono > } else if (event.data === 'EOS') { > fs.writeFileSync('output.raw', Buffer.concat(chunks)); > ws.close(); > } else { > console.error(event.data); // {"type":"error","data":{...}} > ws.close(); > } > }; > ``` ## Next steps * **Build a voice agent**: [My First Agent](/guides/my-first-agent) * **Put an agent on a phone number**: [Phone agent quickstart](/guides/phone-agent-quickstart) * **Explore the SDK**: [SDK Overview](/sdk/introduction) * **Browse the API**: [REST](/api-reference/rest) and [Streaming](/api-reference/streaming) # Agent Skill Source: https://docs.lokutor.com/guides/agent-skill A drop-in Agent Skill that teaches any AI coding agent how to build with Lokutor. Lokutor publishes an [Agent Skill](https://docs.claude.com/en/docs/agents-and-tools/agent-skills), a small Markdown file you load into an AI coding agent (Claude Code, Claude Desktop, Cursor, or any framework that reads skills) so it knows how to integrate Lokutor without you pasting docs into every prompt. Once loaded, the agent knows the SDK calls for TTS, STT and voice agents, the shared request vocabulary (`voice`, `language`, `speed`, `steps`), the audio formats, the typed error model, and the safety rules around the phone Call Center API. ## Install > [tab] Any agent (skills CLI) > > ```bash theme={null} > npx skills add https://docs.lokutor.com > ``` > > Lists the skills this site publishes and installs the one you pick into your agent's skills directory. > [tab] Claude Code (by hand) > > ```bash theme={null} > mkdir -p .claude/skills/lokutor-voice-ai > curl -fsSL https://docs.lokutor.com/.well-known/skills/lokutor-voice-ai/SKILL.md \ > -o .claude/skills/lokutor-voice-ai/SKILL.md > ``` > > Use `~/.claude/skills/` instead of `.claude/skills/` to have it in every project. > [tab] Claude Desktop / claude.ai > > Download [`SKILL.md`](https://docs.lokutor.com/.well-known/skills/lokutor-voice-ai/SKILL.md), put it in a folder named `lokutor-voice-ai`, zip the folder, and upload it under **Settings → Capabilities → Skills**. > [!NOTE] > > The skill is written from the same sources you can use directly: the [OpenAPI spec](/api-reference/openapi-spec) and [`llms-full.txt`](https://docs.lokutor.com/llms-full.txt). To give an assistant live access instead, add the [MCP servers](/guides/mcp-server): one calls the API, one searches these docs. ## Related * [MCP Servers](/guides/mcp-server): Lokutor's API and docs as MCP servers * [OpenAPI Spec](/api-reference/openapi-spec): the machine-readable API contract * [`llms-full.txt`](https://docs.lokutor.com/llms-full.txt): the complete docs in one file # Best Practices Source: https://docs.lokutor.com/guides/best-practices Production patterns with the Lokutor SDK: error handling by retryable and billing codes, audio timing, interruptions, latency, reconnection, and keeping API keys off clients ## Error handling Use `isRetryable()` to decide whether to retry or show a fatal error, and treat `billing.*` codes as a prompt to top up. The full recipe is in [Error handling](/guides/error-handling). ```typescript theme={null} import { isRetryable } from '@lokutor/sdk'; client.on('error', (error) => { if (error.code.startsWith('billing.')) { showTopUpPrompt(); return; } if (!isRetryable(error)) { showFatalError(error.message); return; } console.warn('Transient error:', error.code); }); ``` ## Timing * Use `audioContext.currentTime` for audio timing (not `Date.now()`) * Use `performance.now()` for UI timestamps * Schedule audio with 10-50ms lead time to avoid glitches ## Interruptions If you play audio yourself, clear your queue when the user interrupts, and only then: `listening` while the agent talks is a tentative barge-in ([Handling Interruptions](/guides/handling-barge-in)). The SDK's own audio managers already do this. ```typescript theme={null} client.on('status', (status) => { if (status === 'interrupted') { audioQueue.clear(); } }); ``` ## Latency * **Stream and play chunks as they arrive**; do not wait for the full response. * **Reuse connections** where you can: each new WebSocket costs a handshake. * **Leave speculative replies on** for voice agents unless token cost matters more than about 255 ms per reply. * `steps` cannot be tuned: the current model always runs 4. Measured figures and more detail are in [Latency](/guides/latency-optimization). ## Reconnection After a dropped connection the SDK reconnects by itself with exponential backoff (2s, 4s, 8s, capped at 10s, max 5 attempts). Each reconnection is a new server session. A session the server ended on purpose is not reconnected: the `ended` event fires. ```typescript theme={null} client.on('status', (status) => { if (status === 'reconnecting') showSpinner(); if (status === 'disconnected') showReconnectButton(); }); ``` ## Audio * Pre-warm AudioContext inside a user gesture (button click), not when the first chunk arrives * Guard against odd-length PCM buffers: trim the last byte if `length % 2 !== 0` * Limit transcript history to avoid memory leaks ## Security * Keep API keys on your server, in environment variables. Never put one in browser or mobile code. * Give browsers short-lived tickets with the SDK's `auth` option ([Secure browser setup](/guides/secure-browser-setup)). * Put your ticket route behind your own login. # Bring your own LLM or agent Source: https://docs.lokutor.com/guides/bring-your-own-llm Keep your own model, graph or agent. Lokutor listens, decides when the caller has finished, runs your tools and speaks; your code supplies the reply. Two ways: an OpenAI-compatible HTTPS endpoint, or your own process answering over the session socket. Already have an agent: a LangGraph or LangChain graph, a LiteLLM or vLLM gateway, a service of your own on any cloud? You don't have to rebuild it. Lokutor handles everything around the model (speech recognition, deciding when the caller has finished, barge-in, speech synthesis, phone lines, tool execution) and your code supplies the intelligence. Both ways use the same conversation format, the OpenAI chat messages, so what you build for one works for the other. | | **Endpoint mode** | **Client mode** | | :- | :- | :- | | Who calls whom | Lokutor's servers call **your URL** | Your **process** answers over the session's WebSocket | | Where your code can run | A **public https** address | **Anywhere**: your laptop, a private network, the same program as the SDK | | Phone calls | Yes | No: there is no SDK process on a phone call | | Secrets | Your endpoint's key is stored with the agent, or sent per session | Nothing to expose: no URL, no key | | Set it in | The agent's config, or the `llm` option of the SDK | `on_llm_request` (Python) / `onLlmRequest` (JS) | If you can run a public endpoint, or you need phone calls, use endpoint mode. If your model or tools sit behind a firewall, or you are developing on a laptop, use client mode. ## Client mode Your model runs in the same process that holds the session. Lokutor sends each conversation to your function; you return the reply, all at once or as you produce it. Lokutor starts speaking at the first sentence, and tells you to stop when the caller speaks over the reply. ```python Python theme={null} from lokutor import VoiceAgentClient def on_llm_request(messages, tools): # messages: OpenAI chat messages. messages[0] is Lokutor's system prompt (your agent's instructions plus # how to speak on a call); use it, extend it or ignore it. for token in my_agent.stream(messages): # a LangGraph graph, a LangChain runnable, an API call ... yield token # a string; text is spoken as it arrives client = VoiceAgentClient( api_key="YOUR_LOKUTOR_KEY", prompt="You are the receptionist of a dental clinic.", on_llm_request=on_llm_request, llm_tools="none", # your agent runs its own tools; see "Tools" below ) client.start_conversation() ``` ```typescript JavaScript theme={null} import { VoiceAgentClient } from '@lokutor/sdk'; const client = new VoiceAgentClient({ apiKey: 'YOUR_LOKUTOR_KEY', prompt: 'You are the receptionist of a dental clinic.', llmTools: 'none', async *onLlmRequest(messages, tools, signal) { for await (const token of myAgent.stream(messages, { signal })) yield token; // signal aborts when the caller interrupts }, }); await client.connect(); ``` The handler may return a string, or a generator (async generators in JavaScript) that yields strings. An exception, or a handler that does not answer within 20 seconds, ends that turn with no reply and is reported in the session as an `error` message. The Python SDK runs each request on its own thread, so a slow model never blocks the microphone. ### LangGraph in the same process ```python theme={null} from langgraph.prebuilt import create_react_agent graph = create_react_agent(model, tools=[lookup_order, refund]) # your tools run in YOUR process def on_llm_request(messages, tools): for chunk, meta in graph.stream({"messages": messages}, stream_mode="messages"): if chunk.content and meta.get("langgraph_node") == "agent": # the node that writes to the caller (name depends on your graph) yield chunk.content ``` ## Endpoint mode Point an agent, or one session, at an OpenAI-compatible chat completions endpoint. ```python Python (one session) theme={null} client = VoiceAgentClient( api_key="YOUR_LOKUTOR_KEY", prompt="You are the receptionist of a dental clinic.", llm={"base_url": "https://agent.example.com/v1", "api_key": "YOUR_ENDPOINT_KEY", "model": "my-agent", "headers": {"X-Tenant": "acme"}, "tools": "auto"}, ) ``` ```typescript JavaScript (one session) theme={null} const client = new VoiceAgentClient({ apiKey: 'YOUR_LOKUTOR_KEY', prompt: 'You are the receptionist of a dental clinic.', llm: { baseUrl: 'https://agent.example.com/v1', apiKey: 'YOUR_ENDPOINT_KEY', model: 'my-agent', headers: { 'X-Tenant': 'acme' } }, }); ``` ```json Agent config (every session and phone call) theme={null} { "llm_provider": "custom", "llm_base_url": "https://agent.example.com/v1", "llm_api_key": "YOUR_ENDPOINT_KEY", "llm_model": "my-agent", "llm_headers": { "X-Tenant": "acme" }, "llm_tools": "auto" } ``` | Field | Required | Meaning | | :- | :- | :- | | `base_url` / `llm_base_url` | Yes | The chat completions URL, or the API base: `https://host/v1` gets `/chat/completions` added. Must be **https** on a **public address**. | | `api_key` | No | Sent as `Authorization: Bearer ...`. Not needed if you authenticate with `headers`. | | `model` | No | The `model` field of the request. Left out when you don't set one. | | `headers` | No | Up to 10 extra request headers (a tenant id, a different auth scheme). `Host`, `Content-Type`, `Content-Length`, `Accept`, `User-Agent` and similar are reserved. An `Authorization` header here replaces the key. | | `tools` | No | `auto` (default): the agent's tools are sent as OpenAI `tools`. `none`: never sent; your agent runs its own. | | `speculative_llm` | No | Off by default for your endpoint (see below). | Don't put a secret in browser code. For a browser, set the endpoint on the agent (the key stays on Lokutor's side) or keep the endpoint behind a gateway that needs no key. ### What your endpoint receives A standard request. Lokutor asks for a stream: ```http theme={null} POST /v1/chat/completions Authorization: Bearer YOUR_ENDPOINT_KEY Content-Type: application/json { "model": "my-agent", "stream": true, "stream_options": { "include_usage": true }, "messages": [ { "role": "system", "content": "# Identity ... # Conversation Context\nYou are the receptionist of a dental clinic. ..." }, { "role": "assistant", "content": "Hola, clínica Sonrisa, ¿en qué puedo ayudarte?" }, { "role": "user", "content": "Quería una cita para una limpieza." } ], "tools": [ { "type": "function", "function": { "name": "book_appointment", "parameters": { } } } ], "tool_choice": "auto" } ``` It answers with a server-sent-event stream of `chat.completion.chunk` (content deltas, optional `tool_calls` deltas, an optional last chunk with `usage`, then `data: [DONE]`). A server that ignores `stream` and returns one `chat.completion` JSON body works too, and a strict server that rejects `stream_options` is retried without it. [`custom_llm_server.py`](https://github.com/lokutor-ai/lokutor-sdk/blob/main/python/examples/custom_llm_server.py) is a complete minimal endpoint (about 60 lines of FastAPI) to wrap any agent. ## Tools Your agent may use Lokutor's tools, its own, or both. | You want | Do this | | :- | :- | | Lokutor's tools: the agent's custom API tools, `end_call`, call transfer, calendar, CRM, knowledge base, web search | Leave `tools` on `auto`. Lokutor sends them as OpenAI `tools`. Reply with a `tool_calls` message (an `llm_tool_call` in client mode); Lokutor runs the tool and calls you again with the conversation plus an `assistant` message holding your call and a `tool` message with the result. This is the standard OpenAI tool loop. | | Your own tools, entirely | Set `tools` to `none` and run them inside your agent, answering with text only. Lokutor never sees them. You give up Lokutor's `end_call` and transfer, since only Lokutor can hang up or transfer a phone call. | | Both | Leave `tools` on `auto`. Call Lokutor's tools through the protocol; run everything else inside your agent. A call to a name that is not one of the tools you were sent isn't executed and gets an error result. | Tool arguments are checked against the tool's schema before it runs. A call with missing, blank or mistyped required arguments isn't executed: you get an error result and can call again or ask the caller. Lokutor's own `ask_expert` and background-task tools are not offered when you bring your own model: you are the intelligence. ## What your model also receives Besides the caller's turns, Lokutor sends a few other chat requests through the same model, so make sure yours treats them as ordinary chat: * the opening line, when the agent speaks first and has no fixed first message; * a check-in after a long silence, with a note that the caller has said nothing; * a summary of a long conversation, to keep it within budget; * after the call, your agent's evaluation and data-collection rules, when you use them (in client mode there is no session left to answer them, so they are skipped). ## What is different from the platform's own model * **Speculative replies are off.** The platform's model starts a reply during the caller's pause and discards it when they keep talking, about 0.85 extra requests per turn. Sending those to your service would multiply its load, so they are off unless you set `speculative_llm` to `true`. * **No fallback.** If your endpoint or your handler fails or is too slow, that turn gets no spoken reply and the session receives an `error` message that says why. Lokutor does not answer with its own model in its place. Your endpoint has 20 seconds to start answering. * **Latency is yours.** Time to first audio is your time to the first sentence plus Lokutor's recognition, turn detection and speech synthesis. Stream, and start with a short sentence: say "Let me check that" before a slow lookup. * **Billing.** The platform minute, recognition and speech are billed as usual. Model tokens are not billed: you pay your own endpoint. See [Pricing](/pricing). * **Security.** Endpoint mode is called from Lokutor's servers, so an address that is not public is refused: `localhost`, private ranges, link-local and cloud-metadata addresses, and a hostname that resolves to one, even through a redirect. For local development, use client mode, or a tunnel such as `cloudflared tunnel --url http://localhost:8000`. ## Protocol reference (client mode) Everything is JSON on the session's WebSocket ([protocol](/guides/websocket-protocol)). | Direction | Message | | :- | :- | | You → Lokutor, once, at connect | `{"type":"llm","data":{"mode":"client","tools":"auto"}}` (the SDKs send it for you) | | Lokutor → you | `{"type":"llm_request","request_id":"r1","messages":[...],"tools":[...]}` | | You → Lokutor | `{"type":"llm_chunk","request_id":"r1","data":"text"}`, any number | | You → Lokutor | `{"type":"llm_tool_call","request_id":"r1","id":"c1","name":"...","arguments":"{...}"}` | | You → Lokutor | `{"type":"llm_done","request_id":"r1"}` or `{"type":"llm_error","request_id":"r1","data":"why"}` | | Lokutor → you | `{"type":"llm_cancel","request_id":"r1"}` when the caller speaks over the reply: stop generating | ## Troubleshooting | You see | Cause | | :- | :- | | An `error` message starting `llm:` about `llm_base_url` | The URL is `http`, local or private. Use https on a public host, or use client mode. | | `error` message `LLM error: custom llm endpoint answered HTTP 401: ...` | Your endpoint refused the key or headers; the status and first bytes of its body are in the message. | | Silence after the caller speaks, then an error about the endpoint not answering | Your model took more than 20 seconds to start. Stream earlier, or answer a short sentence first. | | The agent reads out raw JSON | A tool call came back as text. `tool_calls` arguments must be a JSON string (or object) and the tool name one that was sent. | | Requests hit your endpoint twice per turn | `speculative_llm` is on for the agent. Set it to `false`. | # Browser Setup Source: https://docs.lokutor.com/guides/browser-setup Using the JavaScript SDK in browsers: user-gesture rules for the microphone and AudioContext, ticket-based authentication with the auth option, the audio pipeline, and common pitfalls ## Constraints | Constraint | Solution | | :- | :- | | Microphone and AudioContext need a user gesture | Call `startManaged()` inside a button click handler | | AudioContext starts in `suspended` state | Call `audioContext.resume()` after the user gesture | | No filesystem access for saving audio | Use `Blob` and `URL.createObjectURL` | | Anything in the page is public | Never ship an API key: pass a short-lived ticket from your backend | ## Quick setup (Vite) ```bash theme={null} npm create vite@latest my-app -- --template vanilla-ts cd my-app npm install @lokutor/sdk ``` Do not put your API key in a `.env` file the bundler reads (`VITE_*` variables are inlined into the page). Instead, add a backend route that returns a ticket from `POST /ws-ticket`; [Secure browser setup](/guides/secure-browser-setup) has a complete one. ## Audio pipeline The SDK's `BrowserAudioManager` handles everything: 1. Capture mic at hardware rate 2. Resample to 16 kHz Int16 PCM 3. Send over WebSocket 4. Receive 44.1 kHz Int16 PCM 5. Convert to Float32 and schedule via Web Audio API ## Start on button click ```typescript theme={null} import { VoiceAgentClient } from '@lokutor/sdk'; const client = new VoiceAgentClient({ // Called before every connect and reconnect; your backend returns { ticket }. auth: async () => (await fetch('/api/lokutor-ticket', { method: 'POST' }).then((r) => r.json())).ticket, prompt: 'You are a helpful assistant.', }); startButton.addEventListener('click', async () => { await client.startManaged(); }); ``` On phones, ask for the microphone inside the tap itself with `requestMicrophone()` and pass it to `BrowserAudioManager`; see [Starting a call on a phone](/sdk/agent#starting-a-call-on-a-phone). ## VU meter ```typescript theme={null} setInterval(() => { meter.style.width = `${client.getAmplitude() * 100}%`; }, 50); ``` ## Pitfalls 1. Calling `startManaged()` on page load: browsers block microphone access without a user gesture 2. Putting an API key in the page, including through bundler environment variables 3. Not handling `interrupted` status: if you play audio yourself, clear your queue on interruption # Transfer calls to a person Source: https://docs.lokutor.com/guides/call-transfer Let a phone agent hand a caller to someone on your team, one number or a pool, when it cannot help or the caller asks for a person; if nobody answers, it takes a message A phone agent can hand a call to a person. When it cannot resolve what the caller needs, or the caller asks to speak to someone, it tells them it is putting them through, the caller hears ringing, and your phone rings. When you pick up you hear a one-sentence summary of who is calling and why, and you are connected. If nobody answers, the agent comes back on the line and offers to take a message, so a call is never simply lost. It works for one person (a small business forwarding to the owner's mobile) and for a team (a pool of numbers that ring one after another, or take turns between calls). It is for **phone calls**: calls to one of your [Lokutor numbers](/guides/phone-agent-quickstart) and calls your agent makes. A web or app session has no phone line to hand over. ## 1. Switch it on In the dashboard, open the agent → **Tools** → **Transfer to a person** and switch it on. Then, under **Who and how**: * **Numbers to ring**: one to ten, in international format (`+34 612 345 678`), each with an optional name. Only these numbers are ever called: whatever a caller says, the agent cannot dial a number of its choosing. * **Who rings first** (with several numbers): **In this order** always starts with the first; **Take turns** starts each call with the next number, so a team shares the calls. * **Ring each number for**: 10 to 60 seconds, 20 by default. A mobile's voicemail usually answers after 20 to 30 seconds and would take the call: keep the ring shorter, or turn voicemail off on the phones in the pool. * **Tell them who's calling**: on by default. Before you are connected you hear a short summary, in the agent's voice, of who is calling and what they need. * **When to transfer**: optional, in your own words ("billing questions, or when someone asks for María"). The agent always transfers when the caller asks for a person. * **Only at certain times**: optional weekly hours, in the agent's timezone. Outside them the agent does not transfer; it says nobody is available and offers to take a message. The numbers you can transfer to are the ones Lokutor can call at a published price: landlines in every country on the [rate card](/pricing#phone-calls), and mobiles where the rate card has a mobile price (Spain, France, Germany, Austria, the UK and Ireland). The dashboard tells you as you type if a number cannot be used. ## 2. What the caller hears 1. The agent decides to transfer, and says something like "I'm putting you through to someone, please stay on the line." 2. The caller hears a ringing tone while the first number rings. 3. Someone answers: they hear the summary, then the two of you are connected. The agent leaves the call; nothing it says or plays reaches the conversation, which is not recorded. 4. Nobody answers, the line is busy, the call fails, or the person hangs up before being connected: the next number in the pool rings. When every number has been tried, the agent is back: it says nobody is available right now and offers to take a message (name, a number to call back, and what it is about), and reads it back to the caller. The person's phone shows your Lokutor number as the caller, not the caller's own number. ## 3. After the call In the agent's **Monitor** tab and on the **Conversations** page: * A call handed to a person ends with the outcome **transferred**, and the transcript shows where the agent called the transfer. * A call nobody took is flagged **Nobody took the transfer**, with the message the agent took in the summary and the collected data, so you know who to call back. ## Pricing Once the person answers, the agent stops being billed: no platform time and no language model for the rest of the call. What remains is the phone line, at the [rate card's](/pricing#phone-calls) per-minute prices, per started minute: * the caller's line goes on at its own rate (the rate of your number for a call your agent received), and * the line to the person is a call made to their number (landline or mobile rate). A Spanish caller transferred to a Spanish mobile costs **$0.035 + $0.105 = \$0.14 a minute** while they talk to the person. Transfers need a [first top-up](/pricing#welcome-credit), like any call made to a phone. A number that rings and is not answered costs nothing; one that answers and hangs up during the summary costs that minute of their line. The dashboard's **Usage** page shows the transferred part of a call as its own line, **Call transferred to a person**. The call's length with the person is limited by your balance: when it starts, Lokutor works out how long your balance and overdraft can pay for at those two rates (up to 4 hours), and the call ends there. ## Agent config keys The dashboard writes these keys in the agent's config; you can read them back from the `agents` table like the [other settings](/sdk/tool-calling#built-in-tools). | Key | Type | Default | Meaning | | :- | :- | :- | :- | | `transfer_enabled` | `boolean` | `false` | Offer the transfer on this agent's phone calls. | | `transfer_targets` | `[{ "name", "number" }]` | `[]` | 1 to 10 numbers in E.164. A number that cannot be called is ignored. | | `transfer_strategy` | `"in_order"` \| `"rotate"` | `"in_order"` | `rotate` starts each call with the next number. | | `transfer_ring_seconds` | `number` | `20` | How long each number rings, 10 to 60. | | `transfer_announce` | `boolean` | `true` | Play the summary to the person before connecting. | | `transfer_instructions` | `string` | none | When to transfer, in your words (up to 600 characters). | | `transfer_hours` | object or `null` | `null` (any time) | Weekly ranges like [`calendar_hours`](/sdk/tool-calling#google-calendar-opt-in), in the agent's `timezone`. | The agent sees one tool, `transfer_call` `{ "reason", "summary" }`, which runs on Lokutor's side: you do not register or answer it. # Custom vocabulary Source: https://docs.lokutor.com/guides/custom-vocabulary Give speech recognition the names, brands and terms your callers say (keyterms), for voice agents, POST /stt/transcribe and WS /ws/stt Some words are rare enough that recognition gets them almost right: a surname heard as a common word, a product name split in two. Custom vocabulary (`keyterms`) is a list of the words you expect. When what Lokutor hears is close to one of them, it writes your spelling. It works on voice agents (web and phone calls), on `POST /stt/transcribe` and on live `WS /ws/stt` streams. ## Voice agents In the [dashboard](https://app.lokutor.com), open the agent → **Identity** → **Custom words**, and list the terms one per line or separated by commas: your business name, the people callers ask for, products, streets. They apply to every call to that agent from the next call on. ## `POST /stt/transcribe` Add `keyterms` to the request, as a list of strings or one comma-separated string. With a file upload, send a `keyterms` form field with the comma-separated form. ```json theme={null} { "audio": "", "format": "wav", "language": "es", "keyterms": ["Etxeberria", "Invisalign", "Clínica Sol"] } ``` ```bash theme={null} curl -X POST https://api.lokutor.com/stt/transcribe \ -H "Authorization: Bearer $LOKUTOR_API_KEY" \ -F "audio=@recording.wav" \ -F "language=es" \ -F "keyterms=Etxeberria, Invisalign, Clínica Sol" ``` ## `WS /ws/stt` Put `keyterms` in the first JSON message. They apply to every partial and final transcript of that stream: ```json theme={null} {"language": "es", "keyterms": ["Etxeberria", "Invisalign"]} ``` With the SDKs, pass `keyterms` to `STTClient.transcribe` and to `SpeechToTextClient` ([Speech-to-Text](/sdk/stt)). ## Limits and behaviour * Up to **100** terms of up to **40** characters each. Repeats (ignoring case) and empty entries are dropped. More than that answers `400` `validation.invalid_request_format` on the API. * A term is matched against what was heard across up to three words, so a name heard in pieces is put back together ("su bizarreta" becomes "Zubizarreta") and written in your spelling and casing. Terms of several words ("Clínica Sol") work the same way. * At least one of the words heard must be uncommon in the language, so everyday speech is left as it was said: a keyterm cannot turn "el locutor de radio" into your product name. * All nine recognised languages. Without `language` the language is detected and the keyterms apply to it; sending the language is still best for one-word replies. * No extra charge. # Error Handling Source: https://docs.lokutor.com/guides/error-handling A recipe for handling Lokutor errors: show a top-up prompt on 402 billing.* codes, back off on 429 and 503 (honouring Retry-After), and let the retryable flag decide everything else. Every Lokutor error carries a `code` and a `retryable` flag ([Error Catalog](/api-reference/errors)). Three rules cover almost every case: | What you get | What it means | What to do | | :- | :- | :- | | `402` / `billing.*` | The account cannot pay | Do not retry. Ask a person to top up at [app.lokutor.com/billing](https://app.lokutor.com/billing) (or turn on auto-recharge). | | `429` / `auth.rate_limited` | Too many sessions open at once on the account | Close sessions you no longer need, then retry with backoff. | | `503` | Capacity or a temporary failure | Retry after the `Retry-After` header when there is one, otherwise with exponential backoff. | | Anything else | See `retryable` | `true`: retry with backoff. `false`: fix the request, key, voice or agent; retrying will not help. | ## REST ```typescript theme={null} const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); async function synthesize(body: object, attempts = 4): Promise { for (let attempt = 1; ; attempt++) { const res = await fetch('https://api.lokutor.com/tts/synthesize', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LOKUTOR_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify(body), }); if (res.ok) return res.arrayBuffer(); const err = await res.json().catch(() => ({})); if (res.status === 402) { throw new Error(`Top up needed: ${err.message ?? err.code}`); } // The synthesis 503 has {error, voice, hint} and Retry-After; other errors have {code, retryable}. const retryable = res.status === 503 || res.status === 429 || err.retryable === true; if (!retryable || attempt >= attempts) { throw new Error(`${res.status} ${err.code ?? err.error ?? ''}: ${err.message ?? err.hint ?? ''}`); } const retryAfter = Number(res.headers.get('Retry-After')); await sleep(retryAfter > 0 ? retryAfter * 1000 : Math.min(1000 * 2 ** attempt, 10000)); } } ``` ## JavaScript SDK The SDK raises `LokutorError`, whose `retryable` is set from the code. Register a handler with `on('error', …)` or pass `onError` to the constructor; it is not a property to assign afterwards. ```typescript theme={null} import { VoiceAgentClient, VoiceStyle, Language, isRetryable } from '@lokutor/sdk'; const client = new VoiceAgentClient({ auth: getTicket, agentId: 'your-agent-id' }); client.on('error', (error) => { if (error.code.startsWith('billing.')) { showTopUpPrompt(); // billing.insufficient_balance, billing.topup_required, … } else if (error.code === 'auth.rate_limited') { showToast('Too many calls open. Try again in a moment.'); } else if (error.code === 'session.ended') { showEnded(error.message); // the server ended the call on purpose; no reconnect } else if (!isRetryable(error)) { showFatal(error.message); // e.g. auth.invalid_key, agent.not_found, invalid voice } // Retryable errors on a dropped connection: the SDK reconnects by itself (up to 5 attempts). }); ``` `TTSClient.synthesize()` rejects with a `LokutorError` instead, so wrap it in `try`/`catch`: ```typescript theme={null} try { await tts.synthesize({ text, voice: VoiceStyle.F1, language: Language.ENGLISH, onAudio }); } catch (error) { if (isRetryable(error)) { // e.g. tts.synthesis_failed, or internal.timeout when no audio arrived within 30 s } } ``` ## WebSockets * A `402` refuses the handshake before the socket opens. A browser `WebSocket` only sees close code `1006`, so if a connection fails at once, check the balance. * On `/ws/agent`, `429` refuses the handshake. On `/ws/tts`, the socket opens, sends an `auth.rate_limited` error frame and closes. * Close code `1008` with reason `account balance exhausted` means a call ran the balance out: show the top-up prompt. * Error frames on `/ws/agent` and `/ws/stt` can carry a plain string in `data` instead of the structured object. Treat a string as `internal.error`, retryable. # Game Engines (Unity, Godot) Source: https://docs.lokutor.com/guides/game-engines Give a game character a voice: it listens through the microphone, answers in its own voice from where it stands, moves its mouth, and calls your game functions > [!NOTE] > > Preview. The Unity package and the Godot addon are new; tell us what your game needs at [contact@lokutor.com](mailto:contact@lokutor.com). Add a **Lokutor Agent** to any character and it becomes a voice agent: * it **listens** through the player's microphone (the server notices when the player stops talking), * **answers in its own voice** from where it stands in the world (3D audio), * **moves its mouth** with what it says (blend shape, jaw bone, or a 0..1 value for anything else), * and **calls your game's functions** when the conversation calls for it: sell an item, open a gate, start a quest. These are [tool calls](/sdk/tool-calling), set up as "actions". ## Install > [tab] Unity > > Unity 2021.3 or newer, no other packages. **Window > Package Manager > + > Add package from git URL**: > > ``` > https://github.com/lokutor-ai/lokutor-sdk.git?path=/unity > ``` > [tab] Godot > > Godot 4.3 or newer, pure GDScript. Copy > [`godot/addons/lokutor`](https://github.com/lokutor-ai/lokutor-sdk/tree/main/godot/addons/lokutor) > into your project's `addons/` folder, then **Project > Project Settings > Plugins > Lokutor Voice Agents > > Enable**. Enabling it turns on **Audio > Driver > Enable Input**, which the microphone needs. ## Your first talking character **1. Add the agent** **Unity:** select the character, **Add Component > Lokutor > Lokutor Agent**. **Godot:** add a **LokutorAgent** child node (put it at the head: the voice comes from there). **2. Paste your API key** From [app.lokutor.com](https://app.lokutor.com). Fine while prototyping; see [Shipping](#shipping-keep-the-key-on-your-server) before you release. **3. Describe the character** Write who it is in **Persona**, and pick a **Voice** (`F1`-`F5`, `M1`-`M5`, or a voice from [Voices](/voices-languages-models)) and **Language**. **4. Press Play and talk** The character greets the player and listens. Headphones recommended. To use an agent built in the dashboard (prompt, voice, knowledge, tools), set **Agent Id** and leave Persona, Voice and Language empty. ## Let the character do things Actions are game functions the character can call. Without code, wire them in the editor: Unity's **Game actions** list (a name, when to use it, and an **On Called** event) or Godot's **Game Actions** (`LokutorAction`: a name, when to use it, a target node and method). With arguments, register them in code. The handler runs on the main thread and returns a sentence that tells the character what happened: ```csharp Unity theme={null} using Lokutor; var shopkeeper = GetComponent(); shopkeeper.AddAction("give_item", "Sell an item to the player", args => { string item = args.GetString("item"); inventory.Add(item); gold -= prices[item]; return $"Gave the {item}. The player has {gold} gold left."; }, new ActionParam("item", "Which item", ParamType.String, true, "iron sword", "healing potion")); ``` ```gdscript Godot theme={null} @onready var shopkeeper: LokutorAgent = $Shopkeeper/Head/LokutorAgent func _ready(): shopkeeper.add_action("give_item", "Sell an item to the player", _give_item, {"item": {"type": "string", "description": "Which item", "enum": ["iron sword", "healing potion"]}}) func _give_item(args: Dictionary) -> String: inventory.append(args.item) return "Gave the %s." % args.item ``` ## Events and control ```csharp Unity theme={null} agent.onPlayerSaid.AddListener(text => subtitles.ShowPlayer(text)); agent.onCharacterSaid.AddListener(text => subtitles.ShowNpc(text)); agent.onStateChanged.AddListener(state => thinkingBubble.SetActive(state == AgentState.Thinking)); agent.StartConversation(); // e.g. when the player walks up (turn off Start On Awake) agent.StopConversation(); // when they walk away agent.SetPersona("You are now angry with the player."); ``` ```gdscript Godot theme={null} shopkeeper.character_said.connect(func(text): $Subtitles.text = text) shopkeeper.state_changed.connect(_on_state) # DISCONNECTED, CONNECTING, READY, PLAYER_TALKING, THINKING, SPEAKING shopkeeper.start_conversation() # e.g. when the player walks up (turn off Start On Ready) shopkeeper.stop_conversation() # when they leave shopkeeper.set_persona("You are now angry with the player.") ``` A conversation is billed as agent minutes while it is connected, like any other session: start it when the player engages and stop it when they leave. ## Microphone and echo * **Always** (default): the microphone is open; the server detects turns. * **Push to talk**: hold a key or input action, or call `SetTalking(true)` / `set_talking(true)` from your own input code. * **Mute mic while speaking** (on by default) sends silence while the character's voice can still be heard, through the engine's buffers and the room's echo, so laptop speakers cannot make it answer itself. Turn it off when players wear headphones, so they can interrupt the character. ## Shipping: keep the key on your server An API key inside a game build can be extracted. For a release, let your backend trade the key for a short-lived ticket ([`POST /ws-ticket`](/guides/secure-browser-setup)) and give the agent that: ```csharp Unity theme={null} agent.TicketProvider = async () => await myBackend.GetLokutorTicketAsync(); ``` ```gdscript Godot theme={null} shopkeeper.ticket_provider = func(): return await my_backend.get_lokutor_ticket() ``` ## Platforms | | Unity | Godot | | :- | :- | :- | | Windows, macOS, Linux | Yes | Yes | | Android, iOS | Yes (add a microphone usage description) | Yes (microphone permission in the export preset) | | Web | Not yet: use the [JavaScript SDK](/guides/browser-setup) | Not tested yet | ## Examples The [`godot/`](https://github.com/lokutor-ai/lokutor-sdk/tree/main/godot) folder is a Godot project: press Play to talk to **Brom**, a blacksmith who sells you a sword through an action. Unity's Package Manager has a **Talking blacksmith** sample: add its script to an empty GameObject and press Play. # Handling Interruptions (Barge-in) Source: https://docs.lokutor.com/guides/handling-barge-in How barge-in works on /ws/agent: tentative status listening, interrupted only once the interruption is real, false alarms resolved with speaking or thinking, and what the client should do Barge-in is the ability for a user to interrupt the AI while it is speaking. The server handles detection and confirmation automatically; the client's job is just to react to the `status` messages it sends and clear playback promptly. ## How it works 1. **User starts speaking while the agent is talking.** The server's VAD fires and opens a *tentative* barge-in: it stops sending new audio for the in-flight response, but does not cancel it, and sends `status: listening`. It does **not** send `interrupted` yet, so keep playing the audio you already have. Most short sounds over an agent are not interruptions: a cough, a click, a "mhm", or the agent's own voice leaking back through the microphone (worst in the first second of a call, before the browser's echo canceller has adapted). 2. **Playback stops once the interruption is real.** The server sends `status: interrupted` as soon as either: * the user has **kept talking for 400 ms**, or * their utterance is **confirmed** once it ends: it is long enough (`MinWordsToInterrupt`, relaxed for a single word when the GateTurn barge-in classifier scored the audio as a real interruption; when the user picks up a sentence they paused in, the words of the whole sentence count), is not noise, and is not an echo of the agent's own voice. Stop playback and clear your queues on `interrupted`. A confirmed barge-in also cancels the response, truncates the assistant's context to what the user actually heard, sends `transcript_truncated` with that text, and continues with a `transcript` for what they said. 3. **A false alarm never interrupts anything.** If the utterance turns out to be noise, a backchannel or an echo, the server sends a `status` naming what is true now (`speaking` if the response is still playing or resumes, `thinking` if it was still being generated), and any held audio continues under the *same* `generation`. Because the client was never told to stop, the response simply plays on. If the response had already been stopped and over a second of the user's speech could not be transcribed, the agent asks them to repeat ("Sorry, I didn't catch that...", in the call's language) rather than stay silent. ## GateTurn is confirm-only Earlier revisions of this pipeline let the fast classifier both confirm *and* resolve a tentative barge-in (i.e., proactively declare "false alarm, keep talking"). That resolve path was removed: on real call traffic, genuine interruption attempts scored in the same confidence band as backchannels often enough that the resolve path was vetoing real barge-ins, making the bot impossible to interrupt. GateTurn today **only ever fast-tracks a confirm**. It never resolves a tentative barge-in back down — that decision stays entirely with the pre-existing STT-based heuristics described in step 2 above, which is exactly how barge-in worked before GateTurn was introduced. A wrong confirm just costs one redundant interrupt (STT would likely have confirmed it a few hundred ms later anyway); a wrong resolve would cost the user their ability to interrupt at all, which is why the two paths aren't symmetric. There is no separate "resolve" or "dismiss" message on the wire: a dismissed tentative barge-in is an ordinary `status` message (`speaking` or `thinking`). ## Implementation ```typescript theme={null} client.on('status', (status) => { if (status === 'interrupted') { audioPlayer.stop(); audioBuffer.clear(); } // 'listening' while the agent is talking is only a tentative barge-in: // keep playing. If it was a false alarm, 'speaking' (or 'thinking') follows // and audio for the same generation keeps arriving. }); ``` ## Best practices * Clear audio queues on `status: interrupted`, and only then. Stopping on `listening` would let every cough cut the agent off. * A fast 50ms volume fade-out sounds less jarring than a hard cut. * Treat "a new `audio` message arrives" as "we're speaking again", whatever UI state you are showing. * Don't rely on `MinWordsToInterrupt`-style precision from the client: single-word interjections ("stop", "no", "wait") are still respected server-side if sustained, but very short noise and backchannels never reach you as an interrupt. # Latency Source: https://docs.lokutor.com/guides/latency-optimization Where response time goes in Lokutor TTS and voice agents, measured first-audio figures, and what you can change: connection reuse, streaming playback, speculative replies; steps cannot be tuned ## Text-to-speech First audio arrives in a few hundred milliseconds. Measured on Lokutor's production path: | Measurement | Value | | :- | :- | | Network round trip for the first audio frame, idle path | \~114 ms | | First synthesized chunk, median, with the synthesis pool at its capacity | \~388 ms | What you can do: * **Stream.** Use the WebSocket (`/ws/tts`, or `TTSClient`) and start playback on the first chunk. `POST /tts/synthesize` returns only when the whole clip is done. * **Reuse the connection.** A new WebSocket costs a TLS and WebSocket handshake. Over the raw API you can send several requests on one `/ws/tts` socket. (`TTSClient` opens a new socket per call.) * **Measure it.** `TTSClient.synthesize({ …, onTTFB: (ms) => … })` reports the time from sending the request to the first audio. `steps` cannot be tuned: the current model always runs 4 denoising steps ([Parameters](/voices-languages-models#parameters)). ## Voice agents A reply's latency is the sum of detecting that the caller has finished, transcription, the language model's first sentence, and synthesis of that sentence. The language model is usually the largest part. * **Speculative replies** (`speculative_llm`, on by default) start the reply while the caller pauses. Turns where it lands are answered in about 306 ms instead of about 660 ms. Turning it off saves the tokens of unused speculative replies and makes replies about 255 ms slower on average ([Voice Chat](/api-reference/voice-chat#agent-config)). * **Keep prompts short.** A longer system prompt and knowledge base make the model slower to start. * **Tools add time.** Each tool call is another round trip to your code or to a built-in service; web search adds a few seconds. * **Clear your queue on `interrupted`** and when a new reply starts (`status: thinking` with a newer `generation`), so a new reply is not stuck behind old audio ([WebSocket Protocol](/guides/websocket-protocol#generation-numbers)). # MCP Servers Source: https://docs.lokutor.com/guides/mcp-server Two hosted MCP servers: Lokutor's API as tools, and these docs as a searchable source. Nothing to install. Lokutor runs two [MCP](https://modelcontextprotocol.io) servers. Both are hosted (Streamable HTTP), so adding one to Claude Code, Cursor, VS Code or any other MCP client is a single line. There is nothing to clone or install. | Server | URL | What it gives an AI assistant | | :- | :- | :- | | **Lokutor API** | `https://api.lokutor.com/mcp` | Tools that call the API: voices, languages, models, request limits, status, and speech synthesis | | **Lokutor Docs** | `https://docs.lokutor.com/mcp` | Search and read these docs, so answers about Lokutor come from the current documentation | ## Lokutor API ### Tools | Tool | Does | API key | | :- | :- | :- | | `list_voices` | `GET /voices`: every voice, with id, name, gender and languages | not needed | | `list_languages` | `GET /languages`: the supported language codes | not needed | | `list_models` | `GET /models`: loaded synthesis models and the default | not needed | | `get_server_config` | `GET /config`: the limits a synthesis request is validated against | not needed | | `get_server_status` | `GET /status`: readiness, version, uptime | not needed | | `synthesize_speech` | `POST /tts/synthesize`: returns the audio (WAV, 44.1 kHz, mono) in the tool result | **required**; billed from your balance as text-to-speech ([rate card](/api-reference/rate-card): `tts_per_million_chars`, \$4.10 per million characters on 2026-10-18) | `synthesize_speech` requires `text` (up to 1,000 characters) and `voice` (a slot such as `F1`, or one of your `clone_…` ids), and takes an optional `language`. It also accepts `speed` (0.5–2.0) and `steps` (1–8): accepted for compatibility; no effect on versa-2.0. For longer text, call [`POST /tts/synthesize`](/api-reference/rest) directly. Tools run exactly like the REST endpoints behind them, with the same authentication, balance checks and errors. A rejected key or a balance too low to start (`billing.insufficient_balance`) comes back as a tool error the assistant can read. > [!WARNING] > > The [Call Center API](/api-reference/call-center) (buying numbers, placing outbound calls, bulk-dialing) is **deliberately not exposed**. Those endpoints spend real money and place real calls to real people, with `consent_confirmed` as the only built-in gate. The caller is the confirmation step, and an assistant calling a tool on its own is not that. Real-time voice agents run over [WebSocket](/guides/websocket-protocol), which MCP tools do not model, so they are not tools either. ### Add it Create an API key in the [dashboard](https://app.lokutor.com) and send it as `Authorization: Bearer ` (an `X-API-Key` header also works). Without a key, the five discovery tools still work. > [tab] Claude Code > > ```bash theme={null} > claude mcp add --transport http lokutor https://api.lokutor.com/mcp \ > --header "Authorization: Bearer $LOKUTOR_API_KEY" > ``` > [tab] Cursor > > In `~/.cursor/mcp.json` (or `.cursor/mcp.json` in a project; keep keys out of version control): > > ```json theme={null} > { > "mcpServers": { > "lokutor": { > "url": "https://api.lokutor.com/mcp", > "headers": { "Authorization": "Bearer sk_your_key" } > } > } > } > ``` > [tab] VS Code > > In `.vscode/mcp.json`. VS Code asks for the key once and stores it securely: > > ```json theme={null} > { > "inputs": [ > { "type": "promptString", "id": "lokutor-key", "description": "Lokutor API key", "password": true } > ], > "servers": { > "lokutor": { > "type": "http", > "url": "https://api.lokutor.com/mcp", > "headers": { "Authorization": "Bearer ${input:lokutor-key}" } > } > } > } > ``` > [tab] Claude (web and desktop) > > **Settings → Connectors → Add custom connector**, URL `https://api.lokutor.com/mcp`. Custom connectors cannot send an API key header, so this gives the five discovery tools. Use Claude Code, Cursor or VS Code for `synthesize_speech`. ### Protocol Streamable HTTP, stateless. Every request is a `POST` of one JSON-RPC message (or a batch), answered with `application/json`. There is no session and no server-initiated stream, so `GET` returns `405`. Protocol revisions `2025-11-25`, `2025-06-18`, `2025-03-26` and `2024-11-05` are supported. ```bash theme={null} curl -s https://api.lokutor.com/mcp \ -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_languages","arguments":{}}}' ``` ## Lokutor Docs Gives an assistant `search_lokutor` and a read-only view of every page and the [OpenAPI spec](/api-reference/openapi-spec), so it answers from the current docs instead of from memory. No key needed. > [tab] Claude Code > > ```bash theme={null} > claude mcp add --transport http lokutor-docs https://docs.lokutor.com/mcp > ``` > [tab] Cursor / VS Code > > Open the page menu at the top of any docs page and choose **Connect to Cursor** or **Connect to VS Code**. > [tab] Other clients > > Add a Streamable HTTP server with the URL `https://docs.lokutor.com/mcp`. The page menu's **Copy MCP Server** copies it. ## Related * [Agent Skill](/guides/agent-skill): teaches a coding agent how to build with Lokutor * [OpenAPI Spec](/api-reference/openapi-spec): the machine-readable API contract * [`llms-full.txt`](https://docs.lokutor.com/llms-full.txt): the complete docs in one file # My First Agent Source: https://docs.lokutor.com/guides/my-first-agent Build a browser voice agent in about 10 minutes: a Vite page with a Start button, a tiny Node.js backend that mints ws-tickets so the API key stays off the page, status and a live transcript This guide walks you through building your first voice agent in under 10 minutes. You will create a web page with a single button that starts a conversation, shows the agent's status, and displays the transcript in real time. ## What you will build A web page with: * A **Start** button that requests microphone permission and connects to Lokutor * A **status indicator** that shows whether the agent is listening, thinking, or speaking * A **transcript panel** that displays what the user said and what the agent replied ## Prerequisites * An API key from [app.lokutor.com](https://app.lokutor.com) * A modern browser with microphone support (Chrome, Firefox, Edge, Safari) * Node.js 22 or later ## Step 1: Create the project ```bash theme={null} npm create vite@latest my-first-agent -- --template vanilla-ts cd my-first-agent npm install @lokutor/sdk ``` The API key never goes into the page. A small backend exchanges it for a short-lived ticket, and the page asks the backend for one each time it connects ([Secure browser setup](/guides/secure-browser-setup)). Create `server.mjs` next to `package.json`: ```javascript theme={null} // server.mjs: run with LOKUTOR_API_KEY=sk_... node server.mjs import http from 'node:http'; http.createServer(async (req, res) => { if (req.method !== 'POST' || req.url !== '/api/lokutor-ticket') { res.writeHead(404).end(); return; } // In a real app, check the user's session here before minting a ticket. const r = await fetch('https://api.lokutor.com/ws-ticket', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LOKUTOR_API_KEY}` }, }); res.writeHead(r.ok ? 200 : 502, { 'Content-Type': 'application/json' }); res.end(await r.text()); // {"ticket":"wst_…","expires_in":600} }).listen(3001); ``` Create `vite.config.ts` so the page can reach it during development: ```typescript theme={null} import { defineConfig } from 'vite'; export default defineConfig({ server: { proxy: { '/api': 'http://localhost:3001' } }, }); ``` ## Step 2: Write the HTML Replace `index.html` with: ```html theme={null} My First Agent

My First Agent

Disconnected
``` ## Step 3: Write the agent logic Replace `src/main.ts` with: ```typescript theme={null} import { VoiceAgentClient, VoiceStyle, Language } from '@lokutor/sdk'; const startBtn = document.getElementById('start') as HTMLButtonElement; const statusEl = document.getElementById('status') as HTMLDivElement; const transcriptEl = document.getElementById('transcript') as HTMLDivElement; async function getTicket(): Promise { const res = await fetch('/api/lokutor-ticket', { method: 'POST' }); if (!res.ok) throw new Error('Could not get a ticket'); return (await res.json()).ticket; } const client = new VoiceAgentClient({ auth: getTicket, // called before every connect and reconnect prompt: 'You are a helpful and friendly AI assistant. Keep your answers short and conversational.', voice: VoiceStyle.F1, language: Language.ENGLISH, }); client.on('transcription', (text: string) => { addMessage('user', text); }); client.on('response', (text: string) => { addMessage('agent', text); }); client.on('status', (status: string) => { statusEl.textContent = status; statusEl.className = status; }); client.on('error', (error: any) => { console.error('Agent error:', error); statusEl.textContent = 'Error'; statusEl.className = 'disconnected'; }); startBtn.addEventListener('click', async () => { startBtn.disabled = true; startBtn.textContent = 'Connecting...'; try { await client.startManaged(); startBtn.textContent = 'Connected'; } catch (err) { console.error('Failed to start:', err); startBtn.disabled = false; startBtn.textContent = 'Start Conversation'; } }); function addMessage(role: 'user' | 'agent', text: string) { const div = document.createElement('div'); div.className = `message ${role}`; div.textContent = role === 'user' ? `You: ${text}` : `Agent: ${text}`; transcriptEl.appendChild(div); transcriptEl.scrollTop = transcriptEl.scrollHeight; } ``` ## Step 4: Run it In one terminal: ```bash theme={null} LOKUTOR_API_KEY=sk_your_key_here node server.mjs ``` In another: ```bash theme={null} npm run dev ``` Open `http://localhost:5173` in your browser, click **Start Conversation**, and speak into your microphone. ## How it works 1. `startManaged()` requests microphone permission, calls `getTicket()`, and opens a WebSocket to Lokutor with the ticket 2. The SDK sends your configuration (prompt, voice, language) to the server 3. When you speak, the SDK streams microphone audio to the server 4. The server cleans the audio, detects the end of your turn, transcribes it, asks the language model, and streams the spoken reply back 5. The SDK plays the audio and emits events for transcription, response, and status ## Next steps * Run an agent you built in the dashboard instead: replace `prompt`, `voice` and `language` with `agentId: 'your-agent-id'`. See [Voice Agent](/sdk/agent#running-a-dashboard-agent). * Give your agent **tools** so it can fetch data from your systems. See [Tool Calling](/sdk/tool-calling). * Handle **interruptions**. See [Handling Interruptions](/guides/handling-barge-in). * Put the agent on a **phone number**. See [Phone agent quickstart](/guides/phone-agent-quickstart). * Understand where the **latency** goes. See [Latency](/guides/latency-optimization). More examples are in the SDK repository: [github.com/lokutor-ai/lokutor-sdk](https://github.com/lokutor-ai/lokutor-sdk) (`js/examples`). # Node.js Setup Source: https://docs.lokutor.com/guides/node-js-setup Using the JavaScript SDK on servers and in CLIs: Node.js 22+, a voice agent with NodeAudioManager or your own audio pipe, saving TTS to a file, and shutdown ## Requirements | Requirement | Why | | :- | :- | | Node.js 22 or later | The SDK uses the global `WebSocket`, which Node has without a flag from version 22 | | `speaker` and `node-record-lpcm16` (optional) | Microphone and speaker for a voice agent in a terminal. Not needed for TTS or transcription of files. | | No user gesture | You can call `connect()` immediately | On a server, the API key can be used directly (`apiKey: process.env.LOKUTOR_API_KEY`). Never send it to a browser: give browsers tickets ([Secure browser setup](/guides/secure-browser-setup)). ## Setup ```bash theme={null} npm install @lokutor/sdk # only for microphone and speaker: npm install speaker node-record-lpcm16 ``` `node-record-lpcm16` needs SoX (`brew install sox`, `sudo apt install sox`); `speaker` may need ALSA headers on Linux (`sudo apt install libasound2-dev`). ## Voice agent in a terminal `NodeAudioManager` connects the microphone and the speaker for you: ```typescript theme={null} // agent.mjs — node agent.mjs import { VoiceAgentClient, NodeAudioManager } from '@lokutor/sdk'; const client = new VoiceAgentClient({ apiKey: process.env.LOKUTOR_API_KEY, prompt: 'You are a terminal assistant. Keep answers short.', }); client.on('transcription', (text) => console.log('You:', text)); client.on('response', (text) => console.log('Agent:', text)); client.on('error', (err) => console.error(err.code, err.message)); await client.connect(new NodeAudioManager()); process.on('SIGINT', () => { client.disconnect(); process.exit(0); }); ``` There is no echo cancellation in this path: use headphones, or the agent hears itself through the speakers. To route audio yourself (for example from a telephony bridge), connect without an audio manager, send 16 kHz Int16 mono PCM with `client.sendAudio(chunk)`, and play the 44.1 kHz Int16 mono PCM that arrives on `client.on('audio', …)`. ## Save TTS to a file ```typescript theme={null} // tts.mjs — node tts.mjs import { TTSClient, VoiceStyle, Language } from '@lokutor/sdk'; import fs from 'node:fs'; const client = new TTSClient({ apiKey: process.env.LOKUTOR_API_KEY }); const chunks = []; await client.synthesize({ text: 'Hello from Node.js', voice: VoiceStyle.F1, language: Language.ENGLISH, onAudio: (data) => chunks.push(Buffer.from(data)), }); fs.writeFileSync('output.raw', Buffer.concat(chunks)); // Convert: ffmpeg -f s16le -ar 44100 -ac 1 -i output.raw output.wav ``` For a WAV file in one request with no SDK, use [`POST /tts/synthesize`](/api-reference/rest#post-/tts/synthesize-—-tts-synthesis). # Trace calls with OpenTelemetry Source: https://docs.lokutor.com/guides/opentelemetry Send every voice-agent call to Honeycomb, Grafana, New Relic or your own collector as an OpenTelemetry trace: turns, model requests and tools, with timings and token counts. Never what anyone said. Lokutor can send each of your agent's calls, web and phone, to your observability tool as an [OpenTelemetry](https://opentelemetry.io) trace. A trace shows where a slow turn spent its time (recognition, waiting for the caller to finish, the language model, the first audio), which tools ran and which failed, and how many tokens each request used. Your own spans can sit next to it in the same tool. It is off until you set an endpoint, and it is per account: every agent on the account sends to the same place. ## What a call looks like ``` lokutor.call the call (web or phone) lokutor.agent_turn the agent's opening chat its model request, tokens chat (speculative) a reply started early lokutor.turn last word → first audio chat the reply's request, tokens execute_tool book_appointment a tool call, its outcome chat (after_tools) tokens added after tools ``` Spans are sent in batches every few seconds while the call runs. The `lokutor.call` span itself arrives when the call ends. ## Set it up 1. In the [dashboard](https://app.lokutor.com), open **Settings → Observability**. 2. **Endpoint**: the OTLP endpoint your tool gives you, the value it tells you to put in `OTEL_EXPORTER_OTLP_ENDPOINT`. `/v1/traces` is added unless the address already ends in it. 3. **Headers**: what your tool needs to accept the data, usually an API key. Values are masked once saved. 4. **Save**, then **Send a test trace**. Lokutor exports one span named `lokutor.test` with what you saved and shows your endpoint's answer: accepted, or the error it returned (a wrong key shows as `401`). Calls that start after you save send their trace. Switch **Export** off to stop sending without losing the settings, or **Remove** to delete them. | Tool | Endpoint | Header | | :- | :- | :- | | Honeycomb | `https://api.honeycomb.io` (EU: `https://api.eu1.honeycomb.io`) | `x-honeycomb-team`: your API key | | Grafana Cloud | `https://otlp-gateway-prod-.grafana.net/otlp`, from your stack's **OpenTelemetry** tile | `Authorization`: `Basic ` | | New Relic | `https://otlp.nr-data.net` (EU: `https://otlp.eu01.nr-data.net`) | `api-key`: your license key | | Your own collector | its OTLP/HTTP receiver, e.g. `https://otel.example.com:4318` | whatever it requires | Any tool that accepts OTLP over HTTP works. Lokutor sends protobuf over **https** only, to a **public** address: an endpoint that resolves to a private, loopback or link-local address is refused, as are redirects to plain http. ## Spans and attributes Every span carries the resource attributes `service.name` = `lokutor-voice-agent` and `lokutor.account.id`. Names follow OpenTelemetry's [generative AI conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/) where one exists (`chat`, `execute_tool`, `gen_ai.*`). Lokutor's own are under `lokutor.*`. ### `lokutor.call` The call, from start to hang-up. Span kind `server`. | Attribute | | | :- | :- | | `lokutor.session.id` | the call's session id, as in your call history and webhooks | | `lokutor.channel` | `web` or `phone` | | `lokutor.agent.id` | the agent | | `lokutor.call.turns` | caller turns answered, set when the call ends | ### `lokutor.turn` One caller turn, from the last moment the caller was speaking to the first audio of the reply: the wait the caller hears. | Attribute | Milliseconds of | | :- | :- | | `lokutor.turn.index` | (the turn's number in the call, from 1) | | `lokutor.latency.e2e_ms` | the whole turn: caller's last voiced audio → first audio of the reply | | `lokutor.latency.hangover_ms` | silence needed before the turn was considered over | | `lokutor.latency.stt_ms` | speech recognition | | `lokutor.latency.turn_gate_ms` | deciding the caller had finished (and not just paused) | | `lokutor.latency.llm_ms` | the language-model request | | `lokutor.latency.llm_to_tts_ms` | from the reply to the start of speech synthesis | | `lokutor.latency.tts_first_chunk_ms` | speech synthesis, to the first audio | | `lokutor.latency.ttfa_ms` | first audio, counted from the end of the silence instead of the last voiced audio | A stage that did not run, or could not be timed, is left out rather than sent as 0. ### `lokutor.agent_turn` The agent speaking without the caller having spoken: `lokutor.trigger` is `opening`, `silence_timeout` (a check-in after silence), `farewell`, or `host_note` (after a transfer nobody answered). `lokutor.latency.response_ms` is from the request to its first audio. ### `chat` A language-model request. Span kind `client`, `gen_ai.operation.name` = `chat`. | Attribute | | | :- | :- | | `lokutor.llm.kind` | `reply` (inside its turn), `after_tools`, or `speculative` | | `lokutor.llm.outcome` | speculative requests only: `used`, `unused`, `no_response`, `no_transcript`, `failed` or `cancelled` | | `gen_ai.provider.name` | the provider that answered, when known | | `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens` | tokens, when the provider reported them | Every token is counted once, so adding `gen_ai.usage.*` up over a trace gives the call's total: * **reply**: the turn's request. * **after\_tools**: a turn with tools asks the model again after they run. This span carries what those requests added and has no duration of its own. * **speculative**: to answer faster, Lokutor may start a reply while the caller is still finishing. When the turn uses it, its tokens are on the turn's `reply` span: the speculative span says `used` and carries none (a reply the turn took over while it was still streaming has no speculative span at all). When it is thrown away (`unused` and the other outcomes), its tokens are here: they were spent all the same. ### `execute_tool {name}` A tool call: `gen_ai.tool.name`, and `lokutor.tool.outcome` = `ok`, `failed` or `cancelled` (the call ended, or the caller spoke again first). A failed tool also sets the span's status to error. The error's text is not sent: it can contain your system's URLs or data. ## What is not sent No transcripts, replies, tool arguments, tool results, prompts, phone numbers or error messages: only timings, counts, names you chose (tools, agent id) and outcomes. What was said stays in your call history in the dashboard. ## If your endpoint is down Tracing never slows a call down. Spans are queued in memory and sent in the background. When your endpoint refuses them or does not answer, each batch is retried for about 20 seconds and then dropped. They are not stored for later. **Send a test trace** shows the endpoint's last answer when something looks missing. # Phone Agent Quickstart Source: https://docs.lokutor.com/guides/phone-agent-quickstart Put a dashboard agent on a phone number with the Call Center API: find the agent, search for a local number, buy it bound to the agent, take a call, and place an outbound call. This guide puts one of your agents on a phone number, so that anyone who calls the number talks to it. It uses the [Call Center API](/api-reference/call-center) with `curl`; the dashboard can do the same steps without code. ## Before you start * An agent created in the [dashboard](https://app.lokutor.com). Its prompt, voice, language and tools are what callers get. * An API key in `LOKUTOR_API_KEY` ([Authentication](/authentication)). * A first top-up on the account. Phone numbers and outbound calls are not paid by the welcome credit: before the first top-up these endpoints answer `402` `billing.topup_required`. A number costs **\$5 a month** from your balance, charged when you buy it and then monthly. Calls are billed as agent time and language-model tokens plus the phone line per started minute, by country ([Pricing and billing](/pricing#phone-calls)). ## 1. Find your agent's id ```bash theme={null} curl -s https://api.lokutor.com/callcenter/agents \ -H "Authorization: Bearer $LOKUTOR_API_KEY" ``` ```json theme={null} { "agents": [ { "id": "34da7ae3-0d46-4827-8739-ca6a25dc756c", "name": "Front Desk", "voice": "F2", "language": "es" } ] } ``` ## 2. Search for a number Only local numbers are offered, in the US (`US`), Spain (`ES`), the UK (`UK`), Germany (`DE`), France (`FR`), Italy (`IT`) and Portugal (`PT`). Narrow the search with `region_code` or `locality`; results come 15 per page (`page=2` for more). > [!NOTE] > > In most countries outside the US the regulator requires the account holder's identity and address documents before a number can be activated, and Lokutor cannot collect them yet. Buying such a number is refused with the code `number.documents_required` and nothing is charged. US numbers are activated at once. ```bash theme={null} curl -s "https://api.lokutor.com/callcenter/numbers/search?country_code=ES&locality=Madrid" \ -H "Authorization: Bearer $LOKUTOR_API_KEY" ``` Pick a `phone_number` from the results. The `monthly_cost` shown there is the carrier's figure, not your price. ## 3. Buy it, bound to the agent > [!WARNING] > > This rents the number and charges the first month immediately. There is no confirmation step. ```bash theme={null} curl -X POST https://api.lokutor.com/callcenter/numbers \ -H "Authorization: Bearer $LOKUTOR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"phone_number": "+34910000000", "agent_id": "34da7ae3-0d46-4827-8739-ca6a25dc756c"}' ``` `200` means the number is yours and already routed to the agent. `202` means the order was placed and the number appears in `GET /callcenter/numbers` shortly. ## 4. Call it Call the number from any phone. The agent answers with its first message and holds the conversation. The call appears in the dashboard with its transcript. A call to your number is not answered while the account balance is under \$0.25. ## 5. Route it to another agent later `{id}` is the number's `id` from `GET /callcenter/numbers`, not the phone number itself. ```bash theme={null} curl -X POST https://api.lokutor.com/callcenter/numbers/1234567890/assign \ -H "Authorization: Bearer $LOKUTOR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"agent_id": "another-agent-id"}' ``` ## Outbound calls The same number can call out. `consent_confirmed: true` is required and records that you have a lawful basis to call this person. ```bash theme={null} curl -X POST https://api.lokutor.com/callcenter/dial \ -H "Authorization: Bearer $LOKUTOR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"from": "+34910000000", "to": "+34600000000", "agent_id": "34da7ae3-0d46-4827-8739-ca6a25dc756c", "consent_confirmed": true}' ``` The response's `call_id` lets you [follow the call](/api-reference/call-center#get-/callcenter/call-monitor-—-follow-a-call) and [hang it up](/api-reference/call-center#hang-up-a-call). Which destinations can be dialled is listed under [`/callcenter/dial`](/api-reference/call-center#post-/callcenter/dial-—-place-one-outbound-call). > [!WARNING] > > These endpoints spend money and call real people. Do not let an AI agent or an automated job call them without a person approving each call. # Pipecat Integration Source: https://docs.lokutor.com/guides/pipecat-integration Use Lokutor TTS and STT with the Pipecat voice AI framework. [Pipecat](https://github.com/pipecat-ai/pipecat) is an open-source Python framework for building real-time voice and multimodal conversational AI agents. Lokutor TTS is available as a community integration. ## Installation ```bash theme={null} pip install pipecat-lokutor ``` ## Speech to text `pipecat-lokutor` 0.3.0 adds `LokutorSTTService`, which streams audio to the [`/ws/stt`](/sdk/stt#raw-ws-stt-protocol) WebSocket and returns interim and final transcripts in the nine supported languages. The pipeline must run at 16 kHz. ```python theme={null} from pipecat_lokutor import LokutorSTTService stt = LokutorSTTService(api_key="your_api_key") ``` Lokutor ends a stream after an `end` message, so the service sends `end` when Pipecat's VAD reports that the user stopped speaking and reopens the socket for the next utterance. Pass `finalize_on_vad_stop=False` to rely on the server's own silence timer instead. Custom vocabulary is passed as `keyterms`. ## Usage ```python theme={null} from pipecat_lokutor import LokutorTTSService tts = LokutorTTSService( api_key="your_api_key", voice_id="F1", params=LokutorTTSService.InputParams( language="en", speed=1.0, steps=4, visemes=False, ), ) ``` ### Full Example A complete example using Groq STT + Groq LLM + Lokutor TTS is available in the [repository](https://github.com/lokutor-ai/pipecat-lokutor). ## Features * WebSocket-based streaming TTS * Pay-per-use pricing from a prepaid balance ([rate card](/api-reference/rate-card)) * Automatic reconnection with exponential backoff * Metrics and usage tracking * Full Pipecat frame lifecycle management ## Resources * **Repository:** [https://github.com/lokutor-ai/pipecat-lokutor](https://github.com/lokutor-ai/pipecat-lokutor) * **PyPI:** [https://pypi.org/project/pipecat-lokutor/](https://pypi.org/project/pipecat-lokutor/) * **Pipecat Community Integrations:** [https://docs.pipecat.ai/server/services/community-integrations](https://docs.pipecat.ai/server/services/community-integrations) # Secure Browser Setup Source: https://docs.lokutor.com/guides/secure-browser-setup Keep your API key out of the browser: a backend route that mints a 10-minute wst_ ticket from POST /ws-ticket, and browser code that passes it with the JavaScript SDK's auth option. An API key in browser code can be read by anyone who opens the page, and spends your balance. Instead, keep the key on your server and give the page a **ticket**: a credential that starts with `wst_`, works anywhere a key does, and expires after 10 minutes ([Authentication](/authentication#short-lived-tickets)). ``` browser ──POST /api/lokutor-ticket──▶ your backend ──POST /ws-ticket (key in header)──▶ api.lokutor.com browser ◀────────── { ticket } ────── your backend ◀──────── { ticket, expires_in } ──── browser ──wss://api.lokutor.com/ws/agent?api_key=wst_…──▶ api.lokutor.com ``` ## 1. Backend: mint tickets Put this route behind your own login, so only your signed-in users can get a ticket. Example with Node.js 22+ and Express: ```javascript theme={null} // server.mjs — LOKUTOR_API_KEY stays on the server import express from 'express'; const app = express(); app.post('/api/lokutor-ticket', requireSignedInUser, async (req, res) => { const r = await fetch('https://api.lokutor.com/ws-ticket', { method: 'POST', headers: { Authorization: `Bearer ${process.env.LOKUTOR_API_KEY}` }, }); if (!r.ok) return res.status(502).json({ error: 'could not get a ticket' }); const { ticket, expires_in } = await r.json(); res.json({ ticket, expires_in }); }); function requireSignedInUser(req, res, next) { // Replace with your own session check. next(); } app.listen(3000); ``` The key goes in the `Authorization` (or `X-API-Key`) header. `POST /ws-ticket` does not accept it in the URL. ## 2. Browser: pass the ticket with `auth` `VoiceAgentClient` takes an `auth` callback instead of `apiKey`. The SDK calls it before every connection, including each automatic reconnect, so a session that reconnects after the first ticket expired still gets a valid one. ```typescript theme={null} import { VoiceAgentClient } from '@lokutor/sdk'; async function getTicket(): Promise { const res = await fetch('/api/lokutor-ticket', { method: 'POST', credentials: 'include' }); if (!res.ok) throw new Error('No ticket'); return (await res.json()).ticket; } const client = new VoiceAgentClient({ auth: getTicket, agentId: 'your-agent-id', // or prompt / voice / language for an agent defined in code }); startButton.addEventListener('click', () => client.startManaged()); ``` `TTSClient`, `STTClient` and `SpeechToTextClient` take a credential as `apiKey`. Pass a ticket there, fetched just before use: ```typescript theme={null} import { TTSClient } from '@lokutor/sdk'; const tts = new TTSClient({ apiKey: await getTicket() }); ``` A ticket can be reused until it expires, so one ticket can serve several requests made within its 10 minutes. ## Without the SDK Pass the ticket as `?api_key=`, since the browser `WebSocket` and `EventSource` cannot set headers: ```typescript theme={null} const ticket = await getTicket(); const ws = new WebSocket(`wss://api.lokutor.com/ws/agent?agent_id=your-agent-id&api_key=${ticket}`); ``` ## Checklist * No `sk_` key in any file the browser downloads, including `.env` values your bundler inlines (for example `VITE_*` or `NEXT_PUBLIC_*` variables). * The ticket route requires your own authentication; otherwise anyone can mint tickets on your balance. * Rate-limit the ticket route per user if your app is public. # WebSocket Protocol Source: https://docs.lokutor.com/guides/websocket-protocol The /ws/agent wire protocol message by message: handshake and authentication, configuration order, client and server message types, status values, barge-in, generation numbers, call sounds and reconnection ## Why WebSockets A voice conversation needs audio flowing in both directions at once, interleaved with control messages, for the length of the call. A WebSocket carries all of it on one connection. This page documents the **voice agent** protocol (`/ws/agent`). The plain TTS endpoint (`/ws/tts`) is much simpler — see [Real-time Streaming](/api-reference/streaming). ## Connection lifecycle ### 1. Handshake ``` GET /ws/agent?agent_id=… HTTP/1.1 Upgrade: websocket Connection: Upgrade X-API-Key: sk_... ``` ### 2. Authentication The credential is checked during the handshake. It can be an `Authorization: Bearer` header, an `X-API-Key` header, or the `api_key` query parameter, and it can be an API key or a short-lived `wst_` ticket; browsers, which cannot set WebSocket headers, should pass a ticket as `?api_key=`. See [Authentication](/authentication). A bad credential fails the upgrade with `401`; other handshake refusals are listed in [Voice Chat](/api-reference/voice-chat#connection). ### 3. Configuration The SDK sends JSON messages immediately after connecting, in this order: ```json theme={null} { "type": "voice", "data": "F1" } { "type": "language", "data": "en" } { "type": "tools", "data": [ /* only if any tools are registered */ ] } { "type": "visemes", "data": false } { "type": "prompt", "data": "You are a helpful assistant." } { "type": "rates", "playback": 44100, "input": 16000 } ``` The exact order doesn't matter to the server except for `rates`, which should be sent **last**: receiving it is what releases the "first turn" gate server-side (see [`rates`](#rates) below), so sending it before the rest of the configuration risks the first turn running against stale defaults. ### 4. Streaming * **Client → Server**: Binary Int16 PCM frames (16 kHz, mono) — or, equivalently, a JSON `{"type":"audio","data":""}` message carrying the same PCM bytes (see [Binary vs. JSON audio](#binary-vs-json-audio)). * **Server → Client**: JSON text frames only. Unlike the plain `/ws/tts` endpoint, `/ws/agent` never sends raw binary audio frames — agent audio always arrives as a base64-encoded `audio` JSON message (see below). ## Frame types ### Binary frames: microphone audio | Direction | Format | Sample Rate | Chunk Size | | :- | :- | :- | :- | | Client → Server (mic) | Int16 PCM | 16 kHz | \~320 bytes (20ms) | There is no server → client binary frame on this endpoint — agent audio is always wrapped in a JSON `audio` message (base64-encoded), not sent raw. This differs from `/ws/tts`, which does send raw binary audio frames. ### Binary vs. JSON audio The SDK sends microphone audio as raw binary WebSocket frames. The server also accepts the same audio wrapped in a JSON text message — useful for environments where sending arbitrary binary frames is awkward: ```json theme={null} { "type": "audio", "data": "" } ``` Both forms feed the same audio pipeline; you don't need to pick one exclusively. The SDKs only ever use the binary form. ### Text frames: JSON **Client → Server:** | Type | Payload | Purpose | | :- | :- | :- | | `audio` | `data`: base64 PCM16 | Alternative to a raw binary frame — same effect | | `voice` | `data`: voice ID string | Set/change voice style | | `language` | `data`: language code string | Set/change language | | `prompt` | `data`: string | Set/replace the system prompt | | `tools` | `data`: array of tool definitions | Register/replace LLM tool definitions | | `visemes` | `data`: boolean | Enable/disable lip-sync extraction for subsequent responses | | `pitch` | `data`: number (or numeric string) | Set a pitch-shift amount applied to synthesized audio for this session | | `rates` | *(no payload fields are read by the server)* | Client → server "handshake complete" signal — see [`rates`](#rates) | | `reset` | *(no payload)* | Clear the conversation context for this session | | `tool_result` | `data`: `{ call_id, result }` | Return the result of a client-executed tool call | **Server → Client:** | Type | Payload | When | | :- | :- | :- | | `status` | `data`: see [status values](#status-values) | Connection/state changes and message acknowledgments | | `server_rates` | `playback`, `input` (sample rates in Hz) | Once on connect, and again in response to a client `rates` message | | `transcript` | `role` (`user`\|`agent`), `data`, optional `partial: true` | Speech transcribed (user) or agent text response. `partial: true` marks interim user text; the final line follows without it | | `transcript_truncated` | `role: "agent"`, `data`, `full`, `emitted` | The user cut the agent off. `data` is what they heard, ending in `…` (empty if nothing). If `emitted` is true, replace the agent `transcript` whose text was `full`; otherwise add `data` as a new agent line | | `transcript_revised` | `role: "user"`, `data`, `previous` | The user's paused sentence and its continuation were transcribed as one turn. Replace the last user line (`previous`) with `data` and drop any agent line after it | | `audio` | `data`: base64 PCM16, `generation`: int | Agent speech, chunked | | `visemes` | array of `{ v, c, t }` | Lip-sync metadata, if `visemes` was enabled | | `tool_call` | `name`, `arguments` (JSON string), `call_id` | The LLM wants to invoke a tool | | `error` | `data`: a structured error object (`code`, `message`, `detail`, `retryable`) or a plain string | Invalid configuration (structured) or a pipeline error (may be a string) | | `session_limit` | `data`: `{ seconds, reason }` | Once, right after `connected`, when the session has a time limit (today only the key-less demo on lokutor.com, `reason: "demo"`); the server closes the socket with code 1008 when it runs out. API-key sessions never receive it | #### `rates` The SDK sends `{"type":"rates","playback":44100,"input":16000}` as the last step of its configuration handshake. The server does **not** currently read `playback`/`input` from this message — it treats *receipt* of any `rates` message as "the client has finished configuring the session" and uses that to release the gate on the first conversational turn (so the first turn doesn't start against a stale default prompt/voice/language while the client is still mid-handshake). The server then replies with its own actual rates via `server_rates`. If you're implementing the protocol by hand, sending `{"type":"rates"}` with no fields still works — just send it last. #### `status` values `status` messages double as both state-machine transitions and lightweight acks for the config messages above: | `data` value | Meaning | | :- | :- | | `connected` | Handshake complete; also carries a `session_id` field | | `listening` | Server is waiting for/receiving user speech | | `thinking` | LLM is generating a response; carries a `generation` field | | `speaking` | Agent audio is playing | | `interrupted` | The user is really interrupting: stop playback and clear queued audio. See [barge-in](#barge-in) below | | `prompt_set` / `voice_set` / `language_set` / `pitch_set` / `rates_set` / `reset` | Acknowledges the matching client config message | There is no `reconnecting` or `disconnected` value sent by the server — those are purely client-side SDK states emitted while the WebSocket itself is down (see [Reconnection](#reconnection)). ## Barge-in See [Handling Interruptions](/guides/handling-barge-in) for the full picture. Summary for wire-protocol purposes: when the user starts speaking over the agent, the server sends `status: listening` and stops sending new audio for the response, but the barge-in is only *tentative* — keep playing what you have. `status: interrupted` follows once the user has kept talking for 400 ms or the barge-in is confirmed (long enough, not noise, not an echo of the agent's own voice); stop playback then. A confirmed barge-in also truncates the assistant's context to what was heard (`transcript_truncated`). If the tentative barge-in is dismissed as a false alarm, the server sends a `status` naming what's true now — `speaking` if the response is still playing or resumes, `thinking` if it was still generating one — and the response continues under the same `generation`. There's no separate "resumed" type. ## Generation numbers Every response has a `generation` counter, incremented each time the server starts a brand-new turn (not on every barge-in — a dismissed barge-in keeps the same generation). Discard audio from older generations: ```javascript theme={null} ws.onmessage = (event) => { const msg = JSON.parse(event.data); if (msg.type === 'status' && msg.data === 'thinking') { currentGeneration = msg.generation; audioQueue.clear(); } if (msg.type === 'audio' && msg.generation < currentGeneration) { return; // Discard stale audio } }; ``` ## Call sounds An agent can have a **background sound** (a room under the whole call) and a **typing sound** that plays while one of its tools runs. Both are off unless the agent's owner picks them in the dashboard (agent → Tools → Sounds), from the presets or their own file. When an agent has a background sound, the server mixes it into the audio it sends, the same way on web, API and phone calls. Your client plays it like any other audio, with nothing to change. What is different on the wire: * **Audio keeps arriving between replies.** While the agent is quiet the server sends short `audio` messages of the room, about a quarter of a second ahead of playback, so the background never stops. They carry the newest `generation` your client knows, so the stale-audio check above never drops them. * **Clear your queue when a new reply starts** (`status: thinking` with a newer `generation`) and on `status: interrupted`, as above. The server assumes you do: the room queued ahead is then discarded and the reply plays at once. A client that never clears its queue still works, but hears each reply up to \~350 ms later. * **The agent's speech arrives with the room already in it.** Call recordings keep the voice only. ## Reconnection How the server closes the socket says whether to reconnect: | Close code | Meaning | Reconnect? | | :- | :- | :- | | 1000 | The session ended normally (e.g. the agent ended the call, or `nobody has spoken for 5 minutes` when neither side spoke for 5 minutes and the agent said goodbye) | No | | 1008 | A limit was reached; the close reason says which (e.g. the demo's time limit, or `account balance exhausted` when the account's balance ran out during a call, a few seconds after the agent's goodbye) | No | | 4000–4999 | Application-specific end of session | No | | 1001, 1006, 1011–1014 | The server went away or the connection dropped | Yes | The SDK reconnects only in the last case, with exponential backoff: 2s → 4s → 8s → capped at 10s, max 5 attempts. A reconnection is a new server session: send the full configuration again, and reset your generation counter — the new session numbers its responses from 1, so audio compared against the old session's counter would all be discarded as stale. The SDK emits its own `reconnecting` / `disconnected` / `reconnected` client-side events during this process — these are never sent by the server. ## Common pitfalls 1. `binaryType = 'arraybuffer'` is required (default is `blob`) 2. Don't send audio before `onopen` 3. Handle generation counters for interruption 4. Use `audioContext.currentTime`, not `Date.now()`, for viseme timing 5. A tentative barge-in that resolves as a false alarm is announced as an ordinary `status` message (`speaking` or `thinking`, not a separate "resumed" type) — see [Barge-in](#barge-in). 6. Keep streaming audio continuously after the user stops talking, not just while they're speaking. End-of-turn detection is silence-duration-based and only advances when a chunk arrives; a client that stops sending entirely the moment the user goes quiet (rather than continuing to send near-silent mic frames, which any live capture naturally produces) leaves the server with nothing to measure silence against, and the turn never closes. The SDKs already stream continuously and don't need to do anything special here — this only matters if you're driving the wire protocol by hand. # Vercel AI SDK Source: https://docs.lokutor.com/integrations/ai-sdk Use Lokutor text-to-speech and speech-to-text from the Vercel AI SDK with the @lokutor/ai-sdk-provider package. [`@lokutor/ai-sdk-provider`](https://www.npmjs.com/package/@lokutor/ai-sdk-provider) ([source](https://github.com/lokutor-ai/ai-sdk-provider-lokutor)) adds Lokutor to the [Vercel AI SDK](https://ai-sdk.dev) as a speech model and a transcription model. It targets AI SDK 7; it does not work with `ai` 6. ```bash theme={null} npm install ai @lokutor/ai-sdk-provider ``` ```ts theme={null} import { experimental_generateSpeech as generateSpeech, transcribe } from "ai"; // `generateSpeech` in recent versions import { lokutor } from "@lokutor/ai-sdk-provider"; const { audio } = await generateSpeech({ model: lokutor.speech("versa-2.0"), text: "Hello, this is Lokutor.", voice: "F1", language: "en", }); const { text } = await transcribe({ model: lokutor.transcription("lokutor-stt"), audio: audio.uint8Array, providerOptions: { lokutor: { languageCode: "en" } }, }); ``` Set `LOKUTOR_API_KEY` in the environment, or create the provider yourself with `createLokutor({ apiKey })`. ## Behaviour to know * Speech is always WAV. `outputFormat`, `speed` and `instructions` are not supported and produce a warning instead of being sent. * Transcription takes WAV audio only, as the [speech-to-text API](/api-reference/speech-to-text) does. * Speaker labels and the language are set through `providerOptions.lokutor`. * Voices and languages are those of the [Lokutor API](/voices-languages-models). # Dify Source: https://docs.lokutor.com/integrations/dify Use Lokutor text to speech (Versa 2.0) and speech to text (Conv 2.0) as a model provider in Dify. The Lokutor plugin adds two model types to [Dify](https://dify.ai): text to speech (`versa-2.0`) and speech to text (`conv-2.0`), in English, Spanish, Catalan, Galician, Basque, Portuguese, French, Italian and German. Source: [lokutor-ai/dify-plugin-lokutor](https://github.com/lokutor-ai/dify-plugin-lokutor) (MIT). Marketplace listing: submitted to [langgenius/dify-plugins#3621](https://github.com/langgenius/dify-plugins/pull/3621); until it is merged, install the `.difypkg` from the repository. ## Setup 1. Create an API key in the [dashboard](https://lokutor.com). 2. In Dify, open **Settings > Model Provider**, install **Lokutor** and paste the key. 3. Optional: **API Base URL** (default `https://api.lokutor.com/v1`) and **Language** (a language code, or detect from the text or audio). 4. In **System Model Settings**, choose `versa-2.0` for text to speech and `conv-2.0` for speech to text. Saving the key makes one short test synthesis ("Hello") to check it, which is billed like any other request. ## What it calls | Dify model type | Lokutor endpoint | | :- | :- | | Text to speech | [`POST /v1/tts/synthesize`](/api-reference/rest) with `text`, `voice` (`F1`-`F5`, `M1`-`M5`) and, if set, `language` | | Speech to text | `POST /v1/audio/transcriptions` ([OpenAI-compatible](/integrations/openai-compatible)) with `file`, `model` and, if set, `language` | ## Limits * Speech to text takes **WAV only**. Other formats are refused with an error; convert them first. * Text to speech returns WAV (16-bit PCM, 44.1 kHz, mono). Text over 5,000 characters is split on sentence ends and joined into one WAV. * Without a language, synthesis has no language hint; set one for predictable results outside English. * Billing and limits are those of your account. ## What was tested Unit tests with mocked HTTP, and one live round trip against `api.lokutor.com` (the word "Hello" synthesised with `F1`, then that WAV transcribed back). The plugin has **not** yet been run inside a Dify instance (Community Edition or Cloud). # Haystack Source: https://docs.lokutor.com/integrations/haystack Use Lokutor text-to-speech and speech-to-text as components in Haystack 2.x pipelines. `lokutor-haystack` adds two [Haystack](https://haystack.deepset.ai) components: `LokutorTextToSpeech` and `LokutorSpeechToText`. Source: [lokutor-ai/lokutor-haystack](https://github.com/lokutor-ai/lokutor-haystack) (Apache-2.0). ## Install The package is not on PyPI yet. Until it is: ```bash theme={null} pip install lokutor-haystack export LOKUTOR_API_KEY=your_key ``` The key is a Haystack `Secret` read from `LOKUTOR_API_KEY`, so it is never written into a serialized pipeline. ## Text to speech ```python theme={null} from pathlib import Path from haystack_integrations.components.audio.lokutor import LokutorTextToSpeech tts = LokutorTextToSpeech(voice="F1", language="en") audio = tts.run(text="Hello from Lokutor.")["audio"] # ByteStream, audio/wav audio.to_file(Path("hello.wav")) ``` Calls `POST /v1/tts/synthesize`. `voice` is `F1`-`F5`, `M1`-`M5` or a clone id; `language` is an ISO code (pass it for predictable results). `run` accepts `voice` and `language` overrides, and `run_async` exists. Limits are those of the [REST API](/api-reference/rest): 5,000 characters per call, WAV output (16-bit PCM, 44.1 kHz, mono). ## Speech to text ```python theme={null} from haystack_integrations.components.audio.lokutor import LokutorSpeechToText stt = LokutorSpeechToText(language="en", diarize=True) docs = stt.run(sources=["meeting.wav"])["documents"] print(docs[0].content, docs[0].meta["speakers"]) ``` Calls `POST /v1/speech-to-text`. `sources` are file paths or `ByteStream`s and the output is one `Document` per source. **Lokutor decodes WAV only**: convert other formats first. `meta` carries `file_path`, `language_code`, and, with `diarize=True`, `speakers`; with `include_words=True` the per-word timings in `words`. An unreadable file is logged and skipped; an API error raises `RuntimeError` with Lokutor's message. ## Pipeline example ```python theme={null} from haystack import Pipeline from haystack.components.writers import DocumentWriter from haystack.document_stores.in_memory import InMemoryDocumentStore store = InMemoryDocumentStore() indexing = Pipeline() indexing.add_component("stt", LokutorSpeechToText(language="en")) indexing.add_component("writer", DocumentWriter(document_store=store)) indexing.connect("stt.documents", "writer.documents") indexing.run({"stt": {"sources": ["call.wav"]}}) ``` ## What was tested Unit tests with a mocked HTTP layer on haystack-ai 2.10.0 and 3.4.1, and one live round trip (a short sentence synthesized, then transcribed) against `api.lokutor.com`. Not run: non-English languages, diarization against the live API, `run_async` against the live API, or any real-world pipeline beyond the example above. # Langflow Source: https://docs.lokutor.com/integrations/langflow Use Lokutor text to speech and speech to text as components in Langflow flows. The Lokutor bundle adds two components to [Langflow](https://www.langflow.org): **Lokutor Text to Speech** and **Lokutor Speech to Text**, in English, Spanish, Catalan, Galician, Basque, Portuguese, French, Italian and German. Source: the `lokutor` folder of `lfx-bundles` in [langflow-ai/langflow](https://github.com/langflow-ai/langflow), submitted as [langflow-ai/langflow#16133](https://github.com/langflow-ai/langflow/pull/16133) against the `release-1.14.0` branch. Until it is merged and released, the components are not available in a stock Langflow install. ## Setup 1. Create an API key in the [dashboard](https://app.lokutor.com). 2. Install the bundle's extra (it has no dependencies of its own): `uv pip install "lfx-bundles[lokutor]"`. 3. In the Langflow editor, open **Bundles > Lokutor** and drag a component onto the canvas. 4. Paste the key into **Lokutor API Key**, or store it as a Langflow global variable. ## Components | Component | Lokutor endpoint | Output | | :- | :- | :- | | Lokutor Text to Speech | [`POST /v1/tts/synthesize`](/api-reference/rest) with `text`, `voice` (`F1`-`F5`, `M1`-`M5` or a `clone_...` id), `language` and `temperature` | `Data`: `audio_base64` (WAV), `mime_type`, `sample_rate`, `duration_seconds`, `size_bytes`, `voice`, `language` | | Lokutor Speech to Text | [`POST /v1/speech-to-text`](/api-reference/speech-to-text) with `file`, `language_code`, and optionally `diarize` and `num_speakers` | `Message` (transcript) and `Data` (language, per-word times, speaker labels) | Speech to text reads an uploaded WAV file, or the `Data` from **Lokutor Text to Speech** connected to its **Audio Data** input. If both outputs are connected, one request is made and billed. ## Limits * Speech to text takes **WAV only** (PCM 8 or 16 bit, 8 to 48 kHz, 10 MB; larger only with speaker labels on). Convert other formats first. * Text to speech returns WAV, and text is limited to 10,000 characters per component run. * Without a language, synthesis has no language hint; set one for predictable results outside English. * Errors (invalid key, no balance, unsupported audio) fail the component with the status and message Lokutor returned. ## What was not verified The components were tested against the live API through their Python classes (a "Hello" synthesized and transcribed back) and with mocked-HTTP unit tests. They were not run inside a running Langflow server: the editor rendering, the **Bundles** sidebar entry, and how the Playground displays the audio `Data` were not checked. # LlamaIndex Source: https://docs.lokutor.com/integrations/llamaindex Transcribe audio into LlamaIndex Documents and give agents Lokutor text-to-speech and speech-to-text. Two [LlamaIndex](https://www.llamaindex.ai) packages, both from [lokutor-ai/llama-index-lokutor](https://github.com/lokutor-ai/llama-index-lokutor) (Apache-2.0): | Package | Class | Use | | :- | :- | :- | | `llama-index-readers-lokutor` | `LokutorReader` | Audio file to `Document` (speech to text, optional diarization) | | `llama-index-tools-lokutor` | `LokutorToolSpec` | Agent tools `text_to_speech` and `transcribe_audio` | They are not on PyPI yet. Until they are, install from the repository subdirectories: ```bash theme={null} pip install llama-index-readers-lokutor pip install llama-index-tools-lokutor export LOKUTOR_API_KEY=your_key ``` ## Reader ```python theme={null} from llama_index.core import VectorStoreIndex from llama_index.readers.lokutor import LokutorReader reader = LokutorReader(language="en", diarize=True) # language=None detects it docs = reader.load_data("meeting.wav") index = VectorStoreIndex.from_documents(docs) ``` `load_data` / `aload_data` take a path, bytes or a file-like object and return one `Document`; metadata has `file_path`, `language_code`, and with `diarize=True` the `speakers`. Calls [`POST /v1/speech-to-text`](/api-reference/speech-to-text). **WAV only**: convert MP3/M4A first. ## Agent tools ```python theme={null} from llama_index.core.agent.workflow import FunctionAgent from llama_index.llms.openai import OpenAI from llama_index.tools.lokutor import LokutorToolSpec spec = LokutorToolSpec(voice="F1", language="en") agent = FunctionAgent(tools=spec.to_tool_list(), llm=OpenAI(model="gpt-4.1")) ``` `text_to_speech(text, output_path, voice=None, language=None)` writes a WAV via [`POST /v1/tts/synthesize`](/api-reference/rest) and returns the path; `transcribe_audio(audio_path, language=None)` returns the transcript of a WAV file. ## Why a separate repository LlamaIndex's contribution guide states that the main repository no longer accepts new integration packages, so these are maintained and published independently. ## What was tested Unit tests with a mocked HTTP layer, and one live round trip per package (a short sentence synthesized, then transcribed) against `api.lokutor.com`, on llama-index-core as resolved at build time on 2026-11-03. Not run: an LLM-driven agent calling the tools, the async reader against the live API, non-English languages, or diarization against the live API. # Mastra Source: https://docs.lokutor.com/integrations/mastra-voice Use Lokutor for speech and transcription in Mastra agents through @mastra/voice-openai. `@mastra/voice-openai` passes `options` to the OpenAI client, so a base URL override is enough. ```bash theme={null} npm install @mastra/voice-openai ``` ```ts theme={null} import { OpenAIVoice } from '@mastra/voice-openai'; const options = { baseURL: 'https://api.lokutor.com/v1' }; const apiKey = process.env.LOKUTOR_API_KEY; const voice = new OpenAIVoice({ speechModel: { name: 'tts-1', apiKey, options }, // model name is ignored by Lokutor listeningModel: { name: 'whisper-1', apiKey, options }, speaker: 'F1', // F1-F5, M1-M5, or OpenAI names }); const audio = await voice.speak('Hello from Lokutor.', { language: 'en' }); // WAV stream const text = await voice.listen(audioStream, { filetype: 'wav', language: 'en' }); ``` Notes: * Audio is always WAV regardless of `responseFormat`, and transcription accepts WAV only: pass `filetype: 'wav'`. * The model names are typed as `tts-1` / `whisper-1` in the package; Lokutor ignores them. * `language` is forwarded in the request body (the package spreads extra options into it). * Not supported through this class: Mastra's realtime voice (`@mastra/voice-openai-realtime`). Verified against the live API with `@mastra/voice-openai` (speak, then listen on the result). A runnable copy is in [lokutor-ai/openai-compatible-examples](https://github.com/lokutor-ai/openai-compatible-examples/tree/main/mastra). # n8n Source: https://docs.lokutor.com/integrations/n8n Use Lokutor text-to-speech and speech-to-text in n8n workflows with the n8n-nodes-lokutor community node. [`n8n-nodes-lokutor`](https://www.npmjs.com/package/n8n-nodes-lokutor) ([source](https://github.com/lokutor-ai/n8n-nodes-lokutor)) is a community node for [n8n](https://n8n.io). Install it from **Settings → Community nodes** by entering `n8n-nodes-lokutor`, then create a **Lokutor API** credential with your API key. | Operation | Input | Output | | :- | :- | :- | | Text to Speech | text, voice, language (optionally a cloned voice ID) | WAV audio as binary data | | Speech to Text | binary WAV audio | text, language and duration; optionally words and speaker labels | The node calls the same endpoints as the [REST API](/api-reference/rest) and the [speech-to-text API](/api-reference/speech-to-text), so usage is billed to your wallet at the [published rates](https://api.lokutor.com/v1/pricing). # OpenAI Agents SDK (voice) Source: https://docs.lokutor.com/integrations/openai-agents-sdk-voice Use Lokutor speech-to-text and text-to-speech in the OpenAI Agents SDK VoicePipeline with the lokutor-agents-voice adapter. The Agents SDK's built-in OpenAI voice models cannot be redirected to Lokutor with a base URL alone: the TTS model requests raw 24 kHz PCM (Lokutor always returns a 44.1 kHz WAV) and `transcribe()` uses the Realtime WebSocket API. The [`lokutor-agents-voice`](https://github.com/lokutor-ai/lokutor-agents-voice) adapter calls `/v1/audio/speech` and `/v1/audio/transcriptions` and converts the audio. ```bash theme={null} pip install git+https://github.com/lokutor-ai/lokutor-agents-voice export LOKUTOR_API_KEY=... ``` ```python theme={null} from agents.voice import VoicePipeline, SingleAgentVoiceWorkflow from lokutor_agents_voice import LokutorVoiceModelProvider provider = LokutorVoiceModelProvider(voice="F1", language="en") pipeline = VoicePipeline( workflow=SingleAgentVoiceWorkflow(agent), stt_model=provider.get_stt_model(None), tts_model=provider.get_tts_model(None), ) ``` ## Limits * Push-to-talk input only (`AudioInput`). `StreamedAudioInput` is not implemented; use [`/ws/stt`](/api-reference/speech-to-text) directly. * One synthesis request per text chunk; audio is resampled to 24 kHz with linear interpolation. ## Verification Run against the live API with openai-agents 0.24.0: a TTS to STT round trip and a `VoicePipeline` with an echo workflow. Not run: `SingleAgentVoiceWorkflow` with an LLM, and streamed input. # OpenAI-compatible audio API Source: https://docs.lokutor.com/integrations/openai-compatible Use Lokutor from any client that speaks OpenAI's audio API (Open WebUI, LiteLLM, Home Assistant, the OpenAI SDKs) by changing the base URL and the key. Lokutor answers OpenAI's two audio endpoints, so tools that support an OpenAI-compatible speech provider work with Lokutor by pointing them at `https://api.lokutor.com/v1` with your Lokutor API key. | OpenAI endpoint | Lokutor | Notes | | :- | :- | :- | | `POST /v1/audio/speech` | [text to speech](/api-reference/rest#post-/tts/synthesize-—-tts-synthesis) | JSON `{model, input, voice, speed}` | | `POST /v1/audio/transcriptions` | [speech to text](/api-reference/speech-to-text) | multipart `file`, optional `language` | Billing, limits and errors are those of the underlying endpoints, at the [published rates](https://api.lokutor.com/v1/pricing). ## Text to speech ```bash theme={null} curl https://api.lokutor.com/v1/audio/speech \ -H "Authorization: Bearer $LOKUTOR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"model": "tts-1", "input": "Hello from Lokutor.", "voice": "alloy"}' \ --output hello.wav ``` * `model` is accepted and ignored: every request uses Versa 2.0. * `voice` takes OpenAI's names, mapped to Lokutor voices (`alloy`→`F1`, `nova`→`F2`, `shimmer`→`F3`, `coral`→`F4`, `sage`→`F5`, `echo`→`M1`, `onyx`→`M2`, `fable`→`M3`, `ash`→`M4`, `ballad`→`M5`), or any Lokutor voice directly (`F1`, `es_f3`, a cloned voice id). * `language` is a Lokutor extra field (`en`, `es`, `ca`, `gl`, `eu`, `pt`, `fr`, `it`, `de`); without it the text decides. * **The audio is always WAV**, whatever `response_format` asks for. Clients that play the file or hand it to an audio element work; a client that insists on MP3 bytes does not. ## Speech to text ```bash theme={null} curl https://api.lokutor.com/v1/audio/transcriptions \ -H "Authorization: Bearer $LOKUTOR_API_KEY" \ -F file=@call.wav -F model=whisper-1 -F language=es ``` `response_format` can be `json` (default, `{"text": ...}`), `text`, or `verbose_json` (adds `language`, `duration` and per-word times). `srt` and `vtt` are not supported. WAV audio only, as in the [speech-to-text API](/api-reference/speech-to-text). ## OpenAI SDK ```python theme={null} from openai import OpenAI client = OpenAI(base_url="https://api.lokutor.com/v1", api_key="your_lokutor_key") with client.audio.speech.with_streaming_response.create(model="tts-1", voice="alloy", input="Hello") as r: r.stream_to_file("hello.wav") text = client.audio.transcriptions.create(model="whisper-1", file=open("hello.wav", "rb")).text ``` ## Open WebUI, LiteLLM and others In Open WebUI's **Admin → Settings → Audio**, choose the OpenAI engine for both text to speech and speech to text, set the base URL to `https://api.lokutor.com/v1`, paste your key, and give the voice (`alloy` or a Lokutor voice). In LiteLLM, use the `openai/` prefix with `api_base="https://api.lokutor.com/v1"`. # Semantic Kernel Source: https://docs.lokutor.com/integrations/semantic-kernel Use Lokutor text-to-speech and speech-to-text through Semantic Kernel's OpenAI audio connectors. Semantic Kernel's OpenAI audio connectors accept a pre-built client, so a base URL override is enough. ## Python ```python theme={null} from openai import AsyncOpenAI from semantic_kernel.connectors.ai.open_ai import ( OpenAIAudioToText, OpenAIAudioToTextExecutionSettings, OpenAITextToAudio, OpenAITextToAudioExecutionSettings) from semantic_kernel.contents import AudioContent client = AsyncOpenAI(api_key=os.environ["LOKUTOR_API_KEY"], base_url="https://api.lokutor.com/v1") tts = OpenAITextToAudio(ai_model_id="tts-1", async_client=client) stt = OpenAIAudioToText(ai_model_id="whisper-1", async_client=client) audio = await tts.get_audio_contents( "Hello from Lokutor.", OpenAITextToAudioExecutionSettings(voice="alloy", response_format="wav")) open("out.wav", "wb").write(audio[0].data) text = await stt.get_text_contents( AudioContent.from_audio_file("out.wav"), OpenAIAudioToTextExecutionSettings(language="en")) ``` Notes: the Python `voice` field only accepts OpenAI voice names, which Lokutor maps onto its voices (`alloy` and the others map onto F1-F5 / M1-M5). Audio is always WAV and STT takes WAV only. Verified against the live API (TTS to STT round trip) with the `semantic-kernel` Python package. Runnable copy: [lokutor-ai/openai-compatible-examples](https://github.com/lokutor-ai/openai-compatible-examples/tree/main/semantic-kernel-python). ## .NET `OpenAITextToAudioService` and `OpenAIAudioToTextService` take an `OpenAIClient`; build it with `new OpenAIClientOptions { Endpoint = new Uri("https://api.lokutor.com/v1") }` and your Lokutor key. **Not run:** the .NET connectors were not tested. # Vapi Source: https://docs.lokutor.com/integrations/vapi Use Lokutor speech-to-text and text-to-speech in a Vapi assistant through an open adapter service, as a custom transcriber and a custom voice. [Vapi](https://vapi.ai) lets you bring your own speech providers: a **custom transcriber** (a WebSocket that receives the call audio and returns transcripts) and a **custom voice** (an HTTP endpoint that returns raw audio for a sentence). Lokutor is not a built-in Vapi provider. The open-source [vapi-lokutor-adapter](https://github.com/lokutor-ai/vapi-lokutor-adapter) implements both of Vapi's protocols and forwards to the Lokutor API, so you can use Lokutor in a Vapi assistant today by running that small service yourself. > [!NOTE] > > The adapter was tested against Vapi's published protocol documentation with a local mock, and against the live Lokutor API. It has not yet been run on a Vapi account. Treat the first call as a test, and tell us if Vapi behaves differently from its documentation. ## How it fits together ``` Vapi ── wss /api/custom-transcriber ──▶ adapter ── wss /ws/stt ───────────▶ api.lokutor.com Vapi ── POST /api/synthesize ──────────▶ adapter ── POST /v1/tts/synthesize ▶ api.lokutor.com ``` | Vapi | What the adapter does | Lokutor endpoint | | :- | :- | :- | | Custom transcriber | Receives Vapi's 16 kHz 16-bit stereo PCM, keeps the customer channel as mono, returns `transcriber-response` messages (`partial` while the caller speaks, `final` at the end of the utterance) | [`WS /ws/stt`](/sdk/stt#raw-ws-stt-protocol) | | Custom voice | Receives Vapi's `voice-request`, synthesizes the text, resamples the 44.1 kHz result to the `sampleRate` Vapi asked for (8000, 16000, 22050, 24000 or 44100 Hz), returns raw mono 16-bit little-endian PCM | [`POST /tts/synthesize`](/api-reference/rest#post-/tts/synthesize-—-tts-synthesis) | Recognition covers English, Spanish, Catalan, Galician, Basque, Portuguese, French, Italian and German ([languages](/voices-languages-models)). Voices are the slots `F1`-`F5` and `M1`-`M5`. Usage is billed to your Lokutor account at the [rate card](/api-reference/rate-card) prices: synthesis per character and recognition per second of audio sent. Every transcriber connection also counts as one of your account's [concurrent sessions](/pricing#limits). ## 1. Run the adapter You need a Lokutor [API key](/authentication) and a public HTTPS address for the adapter (Vapi cannot reach `localhost`; use your own reverse proxy or a tunnel for testing). ```bash theme={null} git clone https://github.com/lokutor-ai/vapi-lokutor-adapter cd vapi-lokutor-adapter docker build -t vapi-lokutor-adapter . docker run -p 3000:3000 \ -e LOKUTOR_API_KEY="$LOKUTOR_API_KEY" \ -e ADAPTER_SECRET="a-long-random-string" \ vapi-lokutor-adapter ``` Always set `ADAPTER_SECRET`: without it, anyone who finds the URL can spend your Lokutor balance. The adapter accepts it as an `x-vapi-secret` header or as `Authorization: Bearer `. The other settings (default voice and language, upstream URL, timeout) are in the repository README. ## 2. Create the credential in Vapi In the Vapi dashboard, add a **Custom Credential** of type **Bearer Token** whose token is your `ADAPTER_SECRET`, and note its id. ## 3. Configure the assistant Vapi does not send a voice id to a custom voice, so put the voice and language in the server URL's query string. For the transcriber, `language` fixes the recognition language; leave it out and Lokutor detects it. ```json theme={null} { "name": "Lokutor assistant", "transcriber": { "provider": "custom-transcriber", "server": { "url": "wss://adapter.example.com/api/custom-transcriber?language=en", "credentialId": "YOUR_VAPI_CUSTOM_CREDENTIAL_ID" } }, "voice": { "provider": "custom-voice", "server": { "url": "https://adapter.example.com/api/synthesize?voice=F1&language=en", "credentialId": "YOUR_VAPI_CUSTOM_CREDENTIAL_ID", "timeoutSeconds": 30 } }, "model": { "provider": "openai", "model": "gpt-4o-mini", "messages": [{ "role": "system", "content": "You are a helpful assistant." }] } } ``` Replace `adapter.example.com` with your adapter's address. Use any language model Vapi supports; the model section is Vapi's, not Lokutor's. ## Behaviour to know about * **The voice is not streamed.** The adapter waits for the whole sentence from `POST /tts/synthesize` and then answers, so time to first audio is the synthesis time of the full sentence plus the network hop to the adapter, not the streaming first-audio latency of `WS /ws/tts`. * **Only the customer channel is transcribed.** Vapi's second (assistant) channel is ignored. * **End of speech is Lokutor's.** An utterance ends after about 0.7 s without speech ([Speech-to-Text](/sdk/stt#live-transcription)); Vapi's own endpointing settings do not apply to a custom transcriber. * **Errors.** If Lokutor refuses a synthesis (unknown voice, balance, capacity) the adapter answers `502`, or `503` with `Retry-After` when synthesis is at capacity, so a Vapi `fallbackPlan` voice can take over. See [Error Handling](/guides/error-handling). * [Expression tags](/api-reference/expression-tags) such as `[laugh]` in the text Vapi sends are passed to Lokutor unchanged. > [!TIP] > > If you want a full voice agent rather than only speech providers, the [hosted agent API](/api-reference/voice-chat) runs recognition, the language model, tools and synthesis in one connection. # Lokutor Source: https://docs.lokutor.com/introduction Voice agents, text-to-speech, speech-to-text and noise cancellation on Lokutor's own speech models, paid per use from a prepaid balance Lokutor builds its own speech models and serves them as a voice API: voice agents that hold a conversation over the web or the phone, text-to-speech, speech-to-text and noise cancellation. You pay per use from a prepaid balance in US dollars, with no plan and no monthly fee. A voice agent costs about 5¢ a minute, language model included. The exact prices are in [Pricing and billing](/pricing), and the live rate card is public JSON at [`GET /v1/pricing`](/api-reference/rate-card). ## What you can build 1. **Voice Agent**: full-duplex conversations over a single WebSocket, on the web or on a phone number. Speech recognition, the language model, the voice and turn-taking run together, with barge-in support. 2. **Streaming TTS**: send text over a WebSocket and receive audio as it is generated, with the first audio in a few hundred milliseconds. A one-shot `POST /tts/synthesize` returns a WAV file. 3. **Speech-to-Text**: transcribe a recorded clip or a live microphone stream. 4. **Noise removal**: clean a recording with `POST /denoise`. Voice agents clean the caller's audio on every call. ## What runs a call | Job | Model | Notes | | :- | :- | :- | | Speech synthesis | **Versa** (`versa-2.0`) | Lokutor's own. 10 voices, 13 languages (9 also understood). | | Turn-taking and barge-in | **Turno** | Lokutor's own. Decides from the audio whether the caller has finished or is interrupting. | | Noise suppression | **Psst** | Lokutor's own. Cleans the call before recognition. | | Speech recognition | Lokutor's own model | Runs on Lokutor's servers. One model for English, Spanish, Catalan, Galician, Basque, Portuguese, French, Italian and German; the text comes back written out (digits, phone numbers, e-mail addresses, punctuation). | The models are small and efficient, and the hosted API serves them on GPUs. When call audio has to stay on your own infrastructure, the full models also run [on-premise](https://lokutor.com/on-premise-voice-ai/). Ito (text-to-speech) and Oído (speech recognition) are the open models for ESP32-class microcontrollers, the [on-device](https://lokutor.com/edge/) tier. See [Voices, Languages & Models](/voices-languages-models) for the voice list and the languages each part covers. ## Audio format | Property | TTS | Voice Agent | | :- | :- | :- | | **Input** | Text | Int16 PCM, 16 kHz, mono | | **Output** | Int16 PCM, 44.1 kHz, mono | Int16 PCM, 44.1 kHz, mono | | **Connection** | WebSocket (`/ws/tts`) or one HTTP request (`POST /tts/synthesize`, WAV) | Persistent WebSocket (`/ws/agent`) | The SDK handles resampling, buffering, and scheduling. ## Building with an AI assistant? These resources let a coding assistant work from the current documentation instead of from memory: | Resource | What it is | | :- | :- | | [API MCP server](/guides/mcp-server) | `https://api.lokutor.com/mcp`: voices, languages, models, limits and speech synthesis as MCP tools | | [Docs MCP server](/guides/mcp-server#lokutor-docs) | `https://docs.lokutor.com/mcp`: search and read these docs | | [Agent Skill](/guides/agent-skill) | `npx skills add https://docs.lokutor.com` installs a skill that teaches an agent how to integrate Lokutor | | [`/llms.txt`](https://docs.lokutor.com/llms.txt) | An index of every page with its description | | [`/llms-full.txt`](https://docs.lokutor.com/llms-full.txt) | Every page in one text file | | [OpenAPI spec](/api-reference/openapi-spec) | The HTTP API as OpenAPI 3.1 | ## Quick links > [card] [Getting Started](/getting-started) > > Make your first API call in under 5 minutes. > [card] [Launch the App](https://app.lokutor.com) > > Create agents, manage API keys, and view usage. > [card] [Pricing and billing](/pricing) > > The prepaid balance, the rate card, and what a call costs. > [card] [SDK Overview](/sdk/introduction) > > JS and Python SDKs. > [card] [API Reference](/api-reference/rest) > > REST and WebSocket API docs. # Pricing and billing Source: https://docs.lokutor.com/pricing The prepaid balance, the rate card, what a call costs, and what happens when the balance runs out Lokutor is paid from a **prepaid balance in US dollars**. You top up, and every session and request is charged against the balance as you use it: agent time and audio per second, the language model per token, phone lines per started minute. There is no plan, no monthly fee and no minimum. Prices are before tax. The rate card is published as JSON at [`GET https://api.lokutor.com/v1/pricing`](/api-reference/rate-card), with no key needed. The figures on this page are from version `2026-10-09.1`; if the two ever disagree, the API is right. ## The rate card | What | Price | Billed | | :- | :- | :- | | Voice agent, platform | \$0.042 a minute | Per second of session | | Language model, input tokens | \$0.44 per million | Per token | | Language model, output tokens | \$0.94 per million | Per token | | Phone line | By country and direction ([below](#phone-calls)) | Per started minute, on top of the agent | | Phone number | \$5 a month | Monthly, from the balance | | Call logged in your CRM | \$0.04 a call | Per call that reaches your CRM | | Web search | \$0.15 a search | Per search that returns an answer | | Text-to-speech API | \$4.10 per million characters | Per character of text synthesized | | Speech-to-text API | \$0.0014 a minute of audio | Per second of audio | | Noise removal API (`/denoise`) | \$0.0014 a minute of audio | Per second of audio | | [Live translation](/api-reference/live-translation) | \$0.055 a minute of speech, all-in | Per second of session time | Nothing is rounded up to the minute except the phone line, which the carrier bills by the started minute. Usage is added up in fractions of a cent over a session and rounded once, when the session is charged. ### What the agent minute covers The platform price covers speech recognition, the voice, turn-taking, noise removal, orchestration and call recording. A session is billed from the moment the connection is accepted (web, app, SDK) or the call is answered (phone) until it closes or hangs up. A session left open with nobody talking is still a session: close the connection when the conversation is over. ### Language model tokens The language model is billed separately, by the token, at one price whichever model provider answers. Every request the agent makes to the model during a session counts: | Category in your usage | What it is | | :- | :- | | Replies | The reply to each turn | | After a tool call | The round that turns a tool's result into a reply | | Speculative replies not used | Replies started during a pause and thrown away because the caller kept talking ([below](#speculative-replies)) | | Greeting and check-ins | The opening line, and the check-in after a silence | | Conversation summary | Folding a long conversation into a summary | | Post-call evaluation | Your agent's evaluation rules, after the call | | Data collection | Your agent's data fields, extracted at the end of the call | | Expert consults | An agent with the expert on asking its more capable model a question ([below](#expert)); billed at its own price | Each request sends the model the agent's instructions and the conversation so far, so input tokens make up most of the count, and an agent with a long system prompt spends more of them on every turn. A typical minute of conversation uses about 20,700 input and 1,300 output tokens, which is about **1¢**, so a typical minute comes to about **5.2¢** in all. Counts come from the model provider's own report. When a provider reports none for a request that was cancelled, its input tokens are estimated and the line is marked as estimated in your usage. An agent set up with **your own language-model provider and key**, or with **your own endpoint or agent** ([Bring your own LLM](/guides/bring-your-own-llm)), is not billed tokens: you pay your provider directly. The platform minute still applies. ### Speculative replies With speculative replies on, the agent starts its answer while the caller pauses, before it is sure they have finished. When the caller has finished, the reply is already on its way: turns it lands in are answered in about **306 ms** instead of about **660 ms**. When the caller keeps talking, that early reply is thrown away, and its tokens are billed as *speculative replies not used*. It is **on by default**, and costs about a third of a cent a minute at a typical prompt (more with a long prompt, since each unused reply resends it). To turn it off for an agent, set `speculative_llm` to `false` in the agent's config. The agent then asks the model only once the caller's turn has ended, and its replies start about 255 ms later on average. | Agent config key | Type | Default | Effect | | :- | :- | :- | :- | | `speculative_llm` | `boolean` | `true` | Start replies during the caller's pause. Unused replies are billed as tokens. | ### Expert An agent can have a second, more capable model behind the fast one that holds the conversation. When the agent is unsure (a date worked out from "next Tuesday", a total, whether a rule in its instructions applies, the exact values for a tool, something its instructions do not say), it asks the expert first and answers from what comes back. The expert never speaks to the caller. Most turns do not use it, and a turn that does takes about a second longer. It is **off by default**. Turn it on with `expert` in the agent's config. Its tokens are billed on their own line, **Expert consults**, at **$1.24 per million input tokens and $1.87 per million output tokens** (the expert model's own price plus the same 25% as the main model); a consult at a typical prompt costs well under a cent. A session where the agent never consults is billed exactly as without it. | Agent config key | Type | Default | Effect | | :- | :- | :- | :- | | `expert` | `boolean` | `false` | Offer the agent the expert. Consults are billed as tokens at the rates above. | | `background_tasks` | `boolean` | `false` | Experimental. Let the agent hand longer jobs to a background worker ([Tool Calling](/sdk/tool-calling#start_task-and-check_task-opt-in-experimental)). Its tokens are billed on the same line. | ### Phone calls A phone call is billed as agent time and tokens, like any session, plus the phone line **per started minute**: a call of 61 seconds is two minutes of line. The rate depends on the direction and country: the country of your number for a call your agent receives, the destination for a call it makes. | Country | Call received | Call made to a landline | Call made to a mobile | | :- | :- | :- | :- | | Spain | \$0.035 | \$0.049 | \$0.105 | | Portugal | \$0.025 | \$0.066 | Not available | | France | \$0.028 | \$0.025 | \$0.084 | | Italy | \$0.035 | \$0.047 | Not available | | Germany | \$0.028 | \$0.028 | \$0.093 | | Austria | \$0.028 | \$0.027 | \$0.087 | | Switzerland | \$0.028 | \$0.098 | Not available | | Belgium | \$0.035 | \$0.084 | Not available | | Netherlands | \$0.035 | \$0.042 | Not available | | Luxembourg | \$0.025 | \$0.084 | Not available | | United Kingdom | \$0.025 | \$0.022 | \$0.077 | | Ireland | \$0.025 | \$0.041 | \$0.077 | | United States | \$0.019 | \$0.025 | Landline rate | | Canada | \$0.021 | \$0.025 | Landline rate | Prices in USD per minute. Mobiles in Portugal, Italy, Switzerland, Belgium, the Netherlands and Luxembourg cannot be called: their carrier rates are above the ceiling Lokutor allows, and dialling one is refused before anything is charged. In the US and Canada, mobile numbers cannot be told apart from landlines and are charged the landline rate. A call that is not answered costs nothing; a call answered by voicemail is an answered call. **Calls transferred to a person.** When your agent [hands a call to someone on your team](/guides/call-transfer) and they answer, the agent stops being billed for the rest of the call. What remains is two phone lines, per started minute at the table above: the caller's line at its own rate, and the line to the person as a call made to their number. A Spanish caller transferred to a Spanish mobile is $0.035 + $0.105 = **\$0.14 a minute** while they talk to the person. A number that rings and is not answered costs nothing. **Phone numbers** are local numbers at **\$5 a month** from the balance: US numbers are activated at once; numbers in Spain, the UK, Germany, France, Italy and Portugal need the account holder's identity and address documents, which Lokutor cannot collect yet, so buying one is refused and nothing is charged. The first month is charged when you buy the number, then once a month. If the balance cannot pay a month, the number is kept for 30 days; after that it is released, and a released number cannot be recovered. Calls made by your agent and phone numbers need a [first top-up](#welcome-credit): the welcome credit does not pay for them. ### APIs * **Text-to-speech** (`/tts/synthesize`, `/ws/tts`) is billed by the characters of text synthesized. If you stop a stream midway, the characters already synthesized are billed. * **Speech-to-text** (`/stt/transcribe`, `/ws/stt`) and **noise removal** (`/denoise`) are billed by the seconds of audio you send. * **Live translation** (`/ws/translate`) is \$0.055 a minute, all-in: recognition, translation and the synthesized voice are included, and nothing is charged on top in tokens, characters or speech-to-text seconds. It is billed per second of session time, from the moment the socket is accepted until it closes, and appears as a `translation` line in your usage. * A request that fails on our side is not billed. ## Worked examples All at the rate card above, with the language model at a typical prompt. **A 3-minute call your agent answers on a Spanish number:** | Line | Amount | | :- | :- | | Platform, 180 seconds × \$0.042 a minute | \$0.126 | | Language model, about 62,100 input and 3,900 output tokens | \$0.031 | | Phone line, 3 started minutes × \$0.035 | \$0.105 | | **Total** | **\$0.262**, about 8.7¢ a minute | At 3 minutes 10 seconds the line is 4 started minutes, \$0.035 more. The same call on a US number is about 7.1¢ a minute; a call your agent makes to a Spanish mobile, about 15.7¢. **1,000 minutes of conversations on the web or in your app:** $42.00 platform + about $10.33 of tokens (20.7 million input, 1.3 million output) = \*\*about $52.33**. With speculative replies off, about $48.79. **A receptionist answering 300 minutes of calls a month on a Spanish number:** 300 minutes at about 8.7¢, plus the number: **about \$31.20 a month**. **Reading 1 million characters aloud with the text-to-speech API:** **$4.10**. Transcribing an hour of audio: **$0.084**. Your own bill depends on your prompt: the dashboard's **Usage** page shows what each session actually cost, line by line. ## Your balance ### Topping up Top up from **Billing** in the [dashboard](https://app.lokutor.com/billing), from **$10 to $2,000** per payment. For a larger amount, write to [contact@lokutor.com](mailto:contact@lokutor.com). * **Currency.** The balance is in US dollars. At checkout you pay in your own currency, converted by Stripe, or you can choose to pay in US dollars. The dashboard shows your balance in dollars with an approximate equivalent in your currency. * **Tax.** VAT or sales tax is added at checkout, on top of the amount: a $10 top-up by an individual in Spain costs $12.10 and adds \$10 to the balance. A business can enter its VAT ID at checkout; a valid EU VAT ID outside Spain is reverse-charged. * **Invoices.** Ask for an invoice when you top up. Every payment also gets Stripe's receipt by email. ### Auto-recharge Optional, and off until you turn it on in Billing. When a charge leaves the balance below a threshold, your saved card is charged a fixed amount: by default, **below $5, add $20**, with a **monthly cap of \$500**, after which auto-recharge stops until the next month and you are told. Auto-recharge is charged in US dollars; your bank converts it. If your bank asks for 3-D Secure, you get an email link to approve the payment. A declined card is retried up to three times. ### Welcome credit New accounts get **\$5 of credit** once their email is confirmed (or on signing up with Google or GitHub), valid for **90 days**: about 95 minutes of a typical web conversation. Until your first top-up, the welcome credit does not pay for calls your agent makes to phones or for phone numbers, and the account can hold 3 sessions at a time. Accounts registered before the balance existed get a credit when they move over. ### Expiry and refunds * **Purchased balance never expires.** The unused part of a top-up is refunded if you ask within **14 days** of it, to [contact@lokutor.com](mailto:contact@lokutor.com), in the currency you paid. * **Credits** (the welcome credit, promotional codes) expire as stated and are not refundable. Credit that expires soonest is used first; purchased balance is used last. ### Itemised usage Every session and request is itemised in the dashboard (**Usage**): platform time, model tokens by category, phone line, extras and API usage, with the rate card version it was charged at. ### Price changes The rate card is versioned. A session is charged entirely at the version in force when it started. Price increases are announced 30 days ahead; decreases apply at once. ## Limits | Limit | Value | | :- | :- | | Sessions at the same time, per account | 3 before the first top-up, 10 after. Higher on request: [contact@lokutor.com](mailto:contact@lokutor.com) | | Balance needed to start a session or request | \$0.25 | | How far a call in progress may take the balance below zero | -\$2 | A session is one open voice-agent conversation (on the web, in an app or on the phone), one open text-to-speech WebSocket (`/ws/tts`) or one open speech-to-text stream (`/ws/stt`). The limit counts the sessions an account has open, all its keys together. Opening a session past your concurrency limit is refused with `429` [`auth.rate_limited`](/api-reference/errors#authentication-errors) ("Too many concurrent sessions"); close one and retry. ### When the balance runs out * **A call in progress is never cut for money mid-sentence.** It continues while the account's balance goes as low as -\$2 (about 38 typical minutes, shared by all of the account's calls in progress). Past that, the agent apologises, says goodbye and hangs up; it does not tell the caller why. On the web, the server closes the socket with code `1008` and the reason `account balance exhausted` a few seconds after the goodbye (30 seconds after asking for it, if the agent has not said it by then). * **New sessions and API requests** are refused with `402` while the balance is under $0.25. The text-to-speech, speech-to-text and noise-removal APIs have no overdraft: they are refused as soon as the balance is under $0.25. * **A call to your number** while the balance is under \$0.25 is not answered. * **A negative balance** is paid back first by your next top-up. ### Sessions nobody speaks on A session is billed for as long as it is open, so one that nobody is using is ended for you: when neither the caller nor the agent has spoken for **5 minutes**, the agent says it is ending the call and goodbye, and hangs up. On the web, the server then closes the socket with code `1000` and the reason `nobody has spoken for 5 minutes`. This covers a browser tab left open and a phone line nobody hung up. A conversation with pauses is never affected: any speech, from either side, starts the 5 minutes again. ## Billing errors | Code | Status | Meaning | What to do | | :- | :- | :- | :- | | `billing.insufficient_balance` | `402` | The balance is below \$0.25, the minimum to start a session or request (or below a phone number's first month, when buying one). | Top up, or turn on auto-recharge. | | `billing.topup_required` | `402` | Calls to phones and phone numbers need a first top-up; the welcome credit does not pay carriers. | Make a first top-up. | | `billing.account_disputed` | `402` | A payment on the account is disputed, and usage is paused until the dispute is resolved. | Write to [contact@lokutor.com](mailto:contact@lokutor.com). | | `billing.limit_reached` | `402` | Only for accounts still on a monthly plan while accounts move over: the plan's limit was reached. | The plan's rules apply until the account moves to the balance: wait for the next period, or turn on overage in Billing. | None of these is retryable as is. On REST endpoints they arrive in the usual [error format](/api-reference/errors). The [Call Center API](/api-reference/call-center) answers `{"code": "...", "error": "..."}` with the same codes. On the WebSocket endpoints (`/ws/agent`, `/ws/tts`, `/ws/stt`) the refusal comes before the connection opens: the handshake answers `402` with the message as plain text, and a browser only sees the connection fail (close code `1006`). If a WebSocket connection fails at the handshake, check the balance in the dashboard. # Voice Agent Source: https://docs.lokutor.com/sdk/agent VoiceAgentClient: run a dashboard agent (agentId) or one defined in code, authenticate a browser with the auth ticket callback, and handle events (transcription, transcription_partial, response, status, tool_call, error), reconnection and phones `VoiceAgentClient` manages a full-duplex WebSocket for real-time conversations. It handles microphone capture, audio playback, STT, LLM, TTS, and interruptions. ## Basic usage > [tab] JavaScript (browser) > > ```typescript theme={null} > import { VoiceAgentClient, VoiceStyle, Language } from '@lokutor/sdk'; > > // auth: called before every connect and reconnect. Your backend returns a fresh > // wst_ ticket from POST /ws-ticket (see Secure browser setup); the API key stays there. > const getTicket = async () => > (await fetch('/api/lokutor-ticket', { method: 'POST' }).then((r) => r.json())).ticket; > > const client = new VoiceAgentClient({ > auth: getTicket, > prompt: 'You are a helpful and friendly AI assistant.', > voice: VoiceStyle.F1, > language: Language.ENGLISH, > }); > > client.on('transcription', (text) => console.log('You:', text)); > client.on('response', (text) => console.log('Agent:', text)); > client.on('status', (status) => console.log('Status:', status)); > client.on('error', (err) => console.error('Error:', err)); > > // Must be called inside a user gesture (button click) > await client.startManaged(); > ``` > [tab] Python > > ```python theme={null} > from lokutor import VoiceAgentClient, VoiceStyle, Language > import os > > def on_transcription(text): > print(f"You: {text}") > > def on_response(text): > print(f"Agent: {text}") > > client = VoiceAgentClient( > api_key=os.environ['LOKUTOR_API_KEY'], > prompt='You are a helpful and friendly AI assistant.', > voice=VoiceStyle.F1, > language=Language.ENGLISH, > on_transcription=on_transcription, > on_response=on_response, > ) > > client.start_conversation() > ``` > > `start_conversation()` uses the local microphone and speakers: install `pip install "lokutor[audio]"`. > > `client.on(event, callback)` also works if you'd rather register handlers after construction — but note it takes the callback as an argument (`client.on('transcription', on_transcription)`), it is not a `@client.on(...)` decorator. ## Running a dashboard agent Pass `agentId` to run an agent you built in the dashboard, with its prompt, voice, language, tools, knowledge base and integrations. `prompt`, `voice` and `language` are then optional, and the SDK sends them only if you set them, as overrides for this session. ```typescript theme={null} const client = new VoiceAgentClient({ auth: getTicket, agentId: '34da7ae3-0d46-4827-8739-ca6a25dc756c' }); await client.startManaged(); ``` For an `agentId` that is not on your account the server refuses the handshake with `404` `agent.not_found`; a browser sees only a failed connection (`ws.close`). ## Options | Option | Type | Default | Description | | :- | :- | :- | :- | | `auth` | `() => string \| Promise` | — | Returns the credential, called before every connect and reconnect. Use it to fetch a `wst_` ticket from your backend. | | `apiKey` | `string` | — | An API key (server-side) or a ticket. Optional when `auth` is given. | | `agentId` | `string` | — | Run one of your dashboard agents | | `prompt` | `string` | — | System prompt for the language model. Required unless `agentId` is set. | | `voice` | `VoiceStyle` | `F1` | Voice slot ([Voices](/voices-languages-models#voices)). With `agentId`, the agent's own unless you set it. | | `language` | `Language`, `'auto'` or `''` | `ENGLISH` | Language. With `agentId`, the agent's own unless you set it. `'auto'` (or `''`, JS 1.9.0) lets the agent follow the caller's language. | | `visemes` | `boolean` | `false` | Lip-sync data. Not available on the current model ([Visemes](/sdk/visemes)). | | `onTranscription`, `onResponse`, `onStatus`, `onError` | functions | — | Constructor callbacks. Each fires once per event, alongside any `on(...)` listeners for the same event. | | `tools` | `ToolDefinition[]` | `[]` | Tool definitions for function calling | | `serverUrl` | `string` | `wss://api.lokutor.com/ws/agent` | Custom endpoint | Replies and the first message can carry [expression tags](/api-reference/expression-tags) (`[breath]`, `[laugh]`, `[sigh]`, and the emotions `[happy]`, `[sad]`, `[angry]`, `[surprised]`, `[fearful]`, `[disgusted]`, `[excited]`, `[anxious]`); to use them, tell the agent in its prompt when to write them. ## Events | Event | Payload | When | | :- | :- | :- | | `transcription` | `string` | A final line of user speech | | `transcription_partial` | `string` | Interim user text while they are still speaking. Not stored in the transcript | | `response` | `string` | Agent text response | | `audio` | `Uint8Array` | Audio chunk received | | `visemes` | `Viseme[]` | Lip-sync data. Not sent on the current model | | `status` | `string` | `listening`, `thinking`, `speaking`, `interrupted`, plus the client-only `reconnecting`/`disconnected` values emitted while the WebSocket itself is down or after the server ended the session (never sent by the server — see [WebSocket Protocol](/guides/websocket-protocol#status-values)) | | `error` | `LokutorError` | Error occurred | | `tool_call` | `{ name, arguments, call_id }` | The model called one of your tools. Fires once per call; pass `call_id` to `submitToolResult` ([Tool Calling](/sdk/tool-calling)) | | `reconnected` | — | Fired (separately from `status`) after a dropped connection successfully reconnects | | `ended` | `{ code, reason }` | The server ended the session on purpose (the agent ended the call, or a limit was reached). No reconnection follows; `error` fires with code `session.ended` and the server's reason | | `session_limit` | `{ seconds, reason }` | The server announced how long this session may still run. Only sessions with a limit receive it (today: the key-less demo on lokutor.com); API-key sessions do not | ## Methods ```typescript theme={null} // Start the conversation (browser) — the recommended entry point await client.startManaged(); // Or connect manually (e.g. to pass a custom AudioManager) await client.connect(); // Update session config mid-conversation client.updatePrompt('You are now a pirate.'); client.updateVoice(VoiceStyle.M2); client.updateLanguage(Language.SPANISH); client.updateTools(newToolDefinitions); // Get conversation history (final lines only; partial transcripts are not stored) const history = client.getTranscript(); // [{ role, text, timestamp }] const text = client.getTranscriptText(); // formatted string // Mute / volume client.toggleMute(); const amp = client.getAmplitude(); // 0–1 // Submit a tool result (call_id from the tool_call event) client.submitToolResult(call_id, result); // End the session client.disconnect(); ``` Also available: the `connected` and `generation` read-only properties, and `onAudio(cb)` / `onVisemes(cb)` as shorthand for `on('audio', cb)` / `on('visemes', cb)`. Full signatures are in the [JavaScript API Reference](/sdks/javascript/reference). ## Status flow ``` listening → thinking → speaking → listening ↑ interrupted ``` ## Reconnection The client reconnects only when the connection drops or the server goes away (WebSocket close codes 1001, 1006, 1011–1014): exponential backoff 2s → 4s → 8s → cap at 10s, max 5 attempts, status `reconnecting` meanwhile. Each reconnection is a **new server session** — the conversation starts over — and reuses the running microphone. When the server closes the session on purpose — 1000 when the agent ends the call, 1008 when a limit is reached, 4xxx for other application reasons — the client does not reconnect. It fires `error` with a `LokutorError` of code `session.ended` whose `message` is the server's reason, then status `disconnected` and the `ended` event. (Before 1.5.0 it reconnected into a fresh session instead.) ## Starting a call on a phone Ask for the microphone inside the tap that starts the call, with `requestMicrophone()`, and pass the result to `BrowserAudioManager` as `microphone` (see the [JavaScript reference](/sdks/javascript/reference)). Asked for later — after the connection opens — iOS Safari can refuse it without showing its prompt, and in the audio session's `'playback'` mode it always does. If the microphone cannot start, `connect()` rejects with code `audio.microphone_unavailable` and the session is closed rather than left talking to nobody. ## Keeping the screen on In the browser, `BrowserAudioManager` keeps the screen awake while the microphone is live (Screen Wake Lock), the way a video player does: a phone that dims and locks mid-call suspends the page's microphone and audio. The lock is taken again when the page returns to the foreground and released when the call ends. Pass `keepAwake: false` to manage this yourself. # Discovery Source: https://docs.lokutor.com/sdk/discovery Read voices, languages, models, limits, status and readiness without an API key, with the SDK static helpers (fetchVoices, fetchConfig, fetchHealth) or curl The discovery endpoints are public: no API key is needed. The JavaScript SDK wraps them as static methods on `VoiceAgentClient`, which call `https://api.lokutor.com` and throw `LokutorError` on failure. ## Methods | Method | Endpoint | Returns | | :- | :- | :- | | `fetchVoices()` | `GET /voices` | `VoiceInfo[]`: the voice slots | | `fetchLanguages()` | `GET /languages` | `LanguageInfo[]` | | `fetchModels()` | `GET /models` | `ModelInfo[]` | | `fetchConfig()` | `GET /config` | `ServerConfig`: request limits | | `fetchStatus()` | `GET /status` | `ServerStatus` | | `fetchHealth()` | `GET /ready` | Readiness: `{ ready, status }` | ```typescript theme={null} import { VoiceAgentClient } from '@lokutor/sdk'; const voices = await VoiceAgentClient.fetchVoices(); const config = await VoiceAgentClient.fetchConfig(); console.log(voices.map((v) => v.id)); // ['F1', 'F2', …, 'M5'] console.log('Max text length:', config.max_text_length); // 5000 ``` Each method takes an optional base URL, for a local server: `VoiceAgentClient.fetchVoices('http://localhost:8080')`. ## cURL equivalents ```bash theme={null} curl -s https://api.lokutor.com/voices curl -s https://api.lokutor.com/languages curl -s https://api.lokutor.com/config curl -s https://api.lokutor.com/ready ``` The response fields are described in the [REST API reference](/api-reference/rest#discovery). # SDK Overview Source: https://docs.lokutor.com/sdk/introduction Install the JavaScript SDK (@lokutor/sdk 1.6, browsers and Node.js 22+) or the Python SDK (lokutor 1.5, Python 3.8+), and choose between TTSClient, STTClient, SpeechToTextClient and VoiceAgentClient The Lokutor SDKs handle the WebSocket connections, audio capture and playback, resampling, and conversation state. The JavaScript and Python SDKs have the same classes. ## Installation > [tab] JavaScript > > ```bash theme={null} > npm install @lokutor/sdk > ``` > > Works in browsers (Vite, React, vanilla) and in Node.js 22 or later (the SDK uses the global `WebSocket`). Browser apps play audio with the Web Audio API. Current version: 1.6.0. > [tab] Python > > ```bash theme={null} > pip install lokutor > ``` > > Requires Python 3.8 or later. That is all you need to call the API. To play or record audio on the local machine (`play=True`, `start_conversation()`, live microphone transcription), install the audio extra, which needs the PortAudio library: > > ```bash theme={null} > brew install portaudio # macOS > sudo apt install portaudio19-dev # Debian / Ubuntu > pip install "lokutor[audio]" > ``` > > Current version: 1.5.0. ## Credentials Create an API key at [app.lokutor.com](https://app.lokutor.com) and keep it on the server: ```bash theme={null} export LOKUTOR_API_KEY=sk_your_key_here ``` In a browser, never use the key itself. Your backend exchanges it for a short-lived ticket and the page passes the ticket: `VoiceAgentClient` fetches one before every connection through its `auth` option. See [Secure browser setup](/guides/secure-browser-setup). ## Clients | Client | Endpoint | Use it for | | :- | :- | :- | | [`TTSClient`](/sdk/tts) | `WS /ws/tts` | Text to streamed audio | | [`STTClient`](/sdk/stt#batch-transcription) | `POST /stt/transcribe` | Transcribe a recorded clip | | [`SpeechToTextClient`](/sdk/stt#live-transcription) | `WS /ws/stt` | Live transcription from a microphone | | [`VoiceAgentClient`](/sdk/agent) | `WS /ws/agent` | Full-duplex conversations, with [tools](/sdk/tool-calling) | [Discovery helpers](/sdk/discovery) read the voices, languages and limits without a key. ## Platform notes * **Browser:** the microphone and `AudioContext` need a user gesture (a click). See [Browser Setup](/guides/browser-setup). * **Node.js:** needs Node.js 22+. For microphone and speaker, install `speaker` and `node-record-lpcm16` and use `NodeAudioManager`. See [Node.js Setup](/guides/node-js-setup). * **Python:** local audio uses PyAudio, installed with `lokutor[audio]`. ## Reference * [JavaScript API Reference](/sdks/javascript/reference) * [Python API Reference](/sdks/python/reference) * Source and examples: [github.com/lokutor-ai/lokutor-sdk](https://github.com/lokutor-ai/lokutor-sdk) (`js/examples`, `python/examples`) # Speech-to-Text Source: https://docs.lokutor.com/sdk/stt Transcribe a recorded clip with STTClient (POST /stt/transcribe) or a live microphone with SpeechToTextClient (WS /ws/stt): accepted audio formats, languages, partial and final transcripts, and the raw /ws/stt protocol Standalone transcription, with no language model and no voice. Use `STTClient` for a single recorded clip, or `SpeechToTextClient` for live transcription from a microphone. Recognition covers all nine languages (English, Spanish, Catalan, Galician, Basque, Portuguese, French, Italian and German) with one model; pass the language when you know it ([Which languages are understood](/voices-languages-models#which-languages-are-understood)). ## Batch transcription `STTClient` sends one complete audio clip to `POST /stt/transcribe` and returns the transcript. > [tab] Node.js > > ```typescript theme={null} > import { STTClient, Language } from '@lokutor/sdk'; > import fs from 'fs'; > > const client = new STTClient({ apiKey: process.env.LOKUTOR_API_KEY! }); > > const result = await client.transcribe({ > audio: new Blob([fs.readFileSync('recording.wav')]), // a Blob is uploaded as a WAV file > language: Language.ENGLISH, > }); > > console.log(result.text); > ``` > [tab] Browser > > ```typescript theme={null} > import { STTClient } from '@lokutor/sdk'; > > // A short-lived ticket from your backend, never your API key (see Secure browser setup). > const { ticket } = await fetch('/api/lokutor-ticket', { method: 'POST' }).then((r) => r.json()); > const client = new STTClient({ apiKey: ticket }); > > // A WAV file from an (MediaRecorder output is WebM/Ogg, which is not accepted) > async function transcribeFile(file: Blob) { > const result = await client.transcribe({ audio: file }); > console.log(result.text); > } > ``` > [tab] Python > > ```python theme={null} > from lokutor import STTClient, Language > import os > > client = STTClient(api_key=os.environ['LOKUTOR_API_KEY']) > > with open('recording.wav', 'rb') as f: > result = client.transcribe(f.read(), language=Language.ENGLISH) > > print(result['text']) > ``` ### Options | Option | Type | Default | Description | | :- | :- | :- | :- | | `audio` | `Blob \| ArrayBuffer \| Uint8Array` (JS) / `bytes` (Python) | **required** | A complete WAV file, or raw PCM16 with `format: "pcm16"`. In JavaScript, pass WAV as a `Blob` (it is sent as a file upload); a buffer is sent as raw PCM16. | | `format` | `"wav" \| "pcm16"` | `"wav"` | Only needed for raw PCM16 input | | `sampleRate` / `sample_rate` | `number` | — | Required when `format` is `"pcm16"`; ignored for WAV (read from the file header) | | `language` | `Language` | `en` | One of `en`, `es`, `ca`, `gl`, `eu`, `pt`, `fr`, `it`, `de`. | | `keyterms` | `string[]` | — | Custom vocabulary: names and terms to write your way when what is heard is close. Up to 100 ([Custom vocabulary](/guides/custom-vocabulary)). | **Accepted audio:** WAV with 8- or 16-bit PCM, mono or stereo, at 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100 or 48000 Hz, up to 10 MB. Anything else is refused with `validation.invalid_request_format`. ### Result | Field | Type | Description | | :- | :- | :- | | `text` | `string` | Full transcript | | `latencyMs` / `latency_ms` | `number` | Server-side processing time | | `engine` | `string` | STT engine used | | `sampleRate` / `sample_rate` | `number` | Sample rate of the processed audio | | `language` | `string` | Detected/used language | | `durationSeconds` / `duration_seconds` | `number` | Audio duration | | `segments` | `array` | Per-segment text with timing, when the engine provides them | ## Live transcription `SpeechToTextClient` streams microphone audio to `WS /ws/stt`. The server detects where each utterance ends: you get partial transcripts while the user is speaking and a final transcript once they stop. An utterance ends after about **0.7 s without speech**, so a short pause between words does not split a sentence, and its final transcript is one recognition pass over the whole utterance (up to 30 s; longer ones are finalised in parts). Stretches with no speech in them, such as background noise or breathing, are not transcribed. > [tab] Browser > > ```typescript theme={null} > import { SpeechToTextClient, Language } from '@lokutor/sdk'; > > const { ticket } = await fetch('/api/lokutor-ticket', { method: 'POST' }).then((r) => r.json()); > > const client = new SpeechToTextClient({ > apiKey: ticket, // short-lived ticket from your backend > language: Language.ENGLISH, > onPartialTranscript: (text) => console.log('...', text), > onFinalTranscript: (text) => console.log('Final:', text), > onError: (err) => console.error(err), > }); > > await client.connect(); // call from a click handler: it asks for the microphone > > // later > client.disconnect(); > ``` > [tab] Node.js > > ```typescript theme={null} > // Node.js 22+, with: npm install speaker node-record-lpcm16 > import { SpeechToTextClient, NodeAudioManager, Language } from '@lokutor/sdk'; > > const client = new SpeechToTextClient({ > apiKey: process.env.LOKUTOR_API_KEY!, > language: Language.ENGLISH, > onFinalTranscript: (text) => console.log('Final:', text), > }); > > await client.connect(new NodeAudioManager()); > ``` > [tab] Python > > Needs `pip install "lokutor[audio]"` for the microphone. > > ```python theme={null} > from lokutor import SpeechToTextClient, Language > import os, time > > client = SpeechToTextClient( > api_key=os.environ['LOKUTOR_API_KEY'], > language=Language.ENGLISH, > on_final_transcript=lambda text: print('Final:', text), > ) > client.start() > > time.sleep(60) > client.stop() > ``` ### Options | Option | Type | Default | Description | | :- | :- | :- | :- | | `apiKey` / `api_key` | `string` | **required** | API key, or in a browser a `wst_` ticket | | `language` | `Language` | `ENGLISH` | ISO language code: English, Spanish, Catalan, Galician, Basque, Portuguese, French, Italian or German ([Which languages are understood](/voices-languages-models#which-languages-are-understood)). The language also sets how the text is written (punctuation, casing, numbers), so a wrong one makes correct words read badly. If speakers may use more than one language, send none on the raw protocol (below) and it is detected. | | `vad` | `"silero" \| "rms"` | `"silero"` | Sent to the server but ignored by the production recognition path | | `keyterms` | `string[]` | — | Custom vocabulary for this stream, applied to partial and final transcripts ([Custom vocabulary](/guides/custom-vocabulary)) | | `onPartialTranscript` / `on_partial_transcript` | `(text) => void` | — | Fires repeatedly mid-utterance with the best guess so far | | `onFinalTranscript` / `on_final_transcript` | `(text) => void` | — | Fires once the utterance ends | | `onError` / `on_error` | `(error) => void` | — | — | | `onStatusChange` | `(status) => void` | — | JS only: `"connecting" \| "connected" \| "disconnected"` | `endUtterance()` / `end_utterance()` finalizes the utterance in progress **and ends the session**: the server sends the last final transcript, then closes. Use it for a "done" button; connect again to transcribe more. ### Raw `/ws/stt` protocol 1. Connect to `wss://api.lokutor.com/ws/stt` with a credential ([Authentication](/authentication)). 2. Send a JSON first message: `{"language": "en"}`, or `{"language": ""}` to have the language detected. Add `"keyterms": ["…"]` for [custom vocabulary](/guides/custom-vocabulary). 3. The server answers `{"type": "status", "data": "ready", "lang": "en"}`. 4. Send binary frames of 16-bit PCM, 16 kHz, mono (about 20 ms each). 5. The server sends `{"type": "transcript", "data": "…", "isFinal": false, "lang": "en"}` while the user speaks, and `isFinal: true` when the utterance ends. 6. Send `{"type": "end"}` to finalize the current utterance and end the session: the server sends any final transcript, then `{"type": "status", "data": "done"}`, and closes. Errors arrive as `{"type": "error", "data": "…"}`, with a plain string in `data`. Each open stream counts as one of your account's concurrent sessions, together with voice-agent calls and `/ws/tts` sockets (3 before the first top-up, 10 after; [Limits](/pricing#limits)). Past that limit the handshake is refused with `429` and the JSON error `auth.rate_limited` ("Too many concurrent speech recognition sessions"), before the socket opens; close a stream you no longer need and retry. A stream's session is released as soon as it closes. ## Which one do I want? * A file the user already recorded or uploaded → `STTClient.transcribe()`. * Live captions, dictation, or transcribing what's coming from a microphone right now → `SpeechToTextClient`. * Building a full voice conversation (LLM responds, TTS speaks back) → [`VoiceAgentClient`](/sdk/agent) instead — it already includes STT as part of the turn. # Tool Calling Source: https://docs.lokutor.com/sdk/tool-calling Client tools defined in OpenAI function format (tool_call fires once with call_id, answer with submitToolResult), and the server-side built-in tools: knowledge base, web search, Google Calendar and CRM The language model can call tools during a conversation. Tools you register from the client are **executed by your code**: the server sends a `tool_call`, you run it and send back the result, and the agent continues with it. Built-in tools ([below](#built-in-tools)) run on the server. ## How it works 1. **Define** tools using the OpenAI function calling schema 2. **Register** them when creating the `VoiceAgentClient` 3. **Respond** to the `tool_call` event, which fires once per call with `{ name, arguments, call_id }` (`arguments` is a JSON string) 4. **Submit** the result with `submitToolResult(call_id, result)`; `result` may be a string or an object ## Defining tools ```typescript theme={null} import { VoiceAgentClient } from '@lokutor/sdk'; const tools = [ { type: 'function', function: { name: 'get_weather', description: 'Get current weather for a city', parameters: { type: 'object', properties: { city: { type: 'string', description: 'City name' } }, required: ['city'] } } } ]; const client = new VoiceAgentClient({ auth: getTicket, // or apiKey: process.env.LOKUTOR_API_KEY on a server prompt: 'You are a helpful assistant.', tools, }); ``` ## Handling tool calls ```typescript theme={null} client.on('tool_call', async ({ name, arguments: args, call_id }) => { if (name === 'get_weather') { try { const result = await fetchWeather(JSON.parse(args).city); client.submitToolResult(call_id, result); } catch (e) { client.submitToolResult(call_id, { error: 'Weather service unavailable' }); } } }); ``` In Python, `on_tool_call` receives `(name, arguments, call_id)`: ```python theme={null} import json def on_tool_call(name, arguments, call_id): if name == "get_weather": city = json.loads(arguments)["city"] client.submit_tool_result(call_id, {"forecast": fetch_weather(city)}) client = VoiceAgentClient(api_key=os.environ["LOKUTOR_API_KEY"], prompt="…", tools=tools, on_tool_call=on_tool_call) ``` ## Multi-step tool chains The agent can chain tool calls — e.g. look up availability, then book it — within a single turn, calling a tool, feeding the result back to the LLM, and calling another tool if the LLM asks for one, before finally speaking a response. Each `tool_call` gets its own `call_id`; answer every one. ## Built-in tools Every voice-agent session (browser and phone) automatically has a `search_knowledge_base` tool available, in addition to whatever you register yourself: ```json theme={null} { "type": "function", "function": { "name": "search_knowledge_base", "description": "Search the knowledge base for information relevant to the user's question.", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "The search query — a question or keywords about what you need to find" } }, "required": ["query"] } } } ``` It searches the documents you've uploaded to that agent's knowledge base (scoped to your `agent_id`) and returns whichever documents' name or content contain the query terms — a straightforward keyword/substring match, not vector or semantic search, so results are exact-text matches rather than "closest in meaning." Write knowledge-base documents with the wording your users are likely to ask about, and keep them reasonably short — matching content is truncated to 2000 characters per document in the result the LLM sees. You don't need to register or implement this tool yourself; it's handled entirely server-side. It only does anything if the agent has an `agent_id` and knowledge-base documents configured — otherwise it returns an empty result. ### `ask_expert` (opt-in) An agent with `expert: true` in its config is also offered `ask_expert(question)`, which puts a question to a more capable model that sees the agent's instructions and the conversation, and returns a short exact answer for the agent to say in its own words or pass to a tool. The agent decides when: it is told to use it for dates relative to today, totals, whether a rule applies, the values for a tool call and facts its instructions do not state, and not for greetings or plain facts. It is handled server-side (nothing to register), limited to eight consults per session, and billed as tokens ([Pricing](/pricing#expert)). A custom tool of yours named `ask_expert` takes precedence. ### `start_task` and `check_task` (opt-in, experimental) An agent with `background_tasks: true` can hand a job that needs several lookups to a background worker with `start_task(goal, tools)` and keep talking. The worker uses only the server-side tools of yours that the agent names, is told not to book, send, change or cancel anything, and works in up to six rounds and 45 seconds. When it finishes, the result reaches the conversation as a note and the agent tells the caller; `check_task(task_id)` shows where a task stands. At most three tasks per session, two at a time, and they end with the session. Tokens are billed like [expert](/pricing#expert) consults. ### `web_search` (opt-in) An agent with **Web search** turned on in the dashboard (agent → Tools → Built-in, stored as `web_search: true` in the agent's config) is also offered a `web_search` tool: ```json theme={null} { "type": "function", "function": { "name": "web_search", "description": "Search the web for current, public information the caller asked about ...", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "A short, specific web search query." } }, "required": ["query"] } } } ``` It runs server-side and returns `{ "answer": "...", "sources": ["page title", ...] }`, a short answer grounded in current search results. The agent is told to treat that answer as information, not instructions. It is **off by default**. Each search adds a few seconds before the agent answers, and results come from the open web. A call can make at most 3 searches, and **each search that returns an answer costs \$0.15** from your balance (the search provider bills per search; see [Pricing and billing](/pricing)). A search that takes longer than 8 seconds returns an error the agent can apologise for. ### Google Calendar (opt-in) Connect a Google account once (agent → Tools → **Google Calendar** → **Connect Google Calendar**; Google asks you to allow access to your calendar, through Composio, the integration service that also runs the CRM connections), then switch it on per agent (`google_calendar: true` in the agent's config). The agent is then offered two tools: * `check_availability` `{ "date": "YYYY-MM-DD" }` returns the free start times that day, e.g. `{ "date": "2026-09-24", "timezone": "Europe/Madrid", "appointment_minutes": 30, "free": ["09:00", "09:30", "11:00"] }`. * `book_appointment` `{ "date", "time": "HH:MM", "caller_name", "caller_phone"?, "caller_email"?, "reason"? }` creates the event on your primary calendar and returns `{ "booked": true, ... }`. With `caller_email`, the caller is sent the invitation, which includes a Google Meet link. If the time was taken in the meantime, it returns `{ "booked": false, "free": [...] }` so the agent can offer another time. The agent reads the email back to the caller before booking. An address that cannot be right (not an address, a made-up subdomain of a mail provider such as `name@company.gmail.com`, or a domain that does not exist) stops the booking with `{ "booked": false, "reason": ... }`, and the agent confirms it with the caller instead of sending the invitation to nobody. Addresses the caller dictates ("ana punto ruiz arroba gmail punto com", "ana dot ruiz at gmail dot com") appear written out (`ana.ruiz@gmail.com`) in the transcript and the collected data. Set when the agent may book in the dashboard (agent → Tools → Google Calendar), or in the agent's config: | Key | Meaning | Default | | - | - | - | | `calendar_hours` | Bookable ranges per weekday, in the agent's timezone: `{"mon": [["09:00","14:00"], ["15:00","18:00"]], "tue": [["09:00","18:00"]], ...}`. A day that is missing or empty is closed. | Monday to Friday, 09:00–18:00 (set by the dashboard) | | `appointment_minutes` | Meeting length, 5–240. Starts fall on the half hour, or the quarter hour for lengths that don't fit it. | `30` | | `buffer_minutes` | Time kept clear before and after every other event, 0–120. | `0` | | `booking_notice_minutes` | How soon a meeting may start, counted from the call, 0–10080. | `15` | | `booking_window_days` | How many days ahead the agent may book, 1–365. | no limit | Agents set up before `calendar_hours` existed use `calendar_open` / `calendar_close` for every day of the week, and keep doing so until you edit their hours. The agent only offers a time the calendar shows as free, and checks again right before booking, so it never books over another event, including one added while the call was going on. When a day is full, `check_availability` also returns `next_available` (the next days with free times) and the week's `bookable_hours`, so the agent can offer alternatives straight away. As the call starts, the agent is also given the free times of the next five bookable days, read from your calendar, so it proposes times that exist rather than guessing a day; it still checks the day again before confirming. Busy times are read from your primary calendar. Disconnecting stops every agent on the account from booking. Both tools run server-side. Like every tool call, they appear in the call's transcript at the moment the agent used them. ### Your CRM (opt-in) Connect your CRM once (agent → Tools → **CRM** → **Connect a CRM**, then pick yours), then switch it on per agent (`crm: true` in the agent's config). Supported: **HubSpot, Salesforce, Zoho CRM, Zoho Bigin, Attio, Capsule and Intercom** (sign in with your CRM account) and **Pipedrive, ActiveCampaign, Copper, Fireberry and Salesflare** (paste an API key from your CRM's settings). The connection belongs to your account, so every agent you switch on uses the same CRM. ActiveCampaign cannot store a contact without an email, so a new caller who gives none is not created there. With it on, three things happen on every call: * **The caller is recognised.** When the call starts, the agent looks the caller up by phone number (the caller's number on an inbound phone call, the number dialled on an outbound one) or by the `caller_phone` / `caller_email` a web session passes (see [Voice Chat](/api-reference/voice-chat#connection)). If the CRM has a record, the agent gets a short summary of it (name, company, email, open deals, the latest note) a few seconds into the call, and uses it instead of asking again. The lookup runs alongside the greeting; it never delays the agent's first words. * **A caller calling from another number can still be recognised.** The agent is offered one server-side tool, `crm_identify_caller` `{ "email"?, "phone"?, "name"? }`, for when the caller was not recognised and tells it who they are. It returns `{ "found": true, "record": "..." }` or `{ "found": false }`, and takes a few seconds, so the agent says it is checking. * **The call is logged.** When it ends, the call's summary, outcome, transcript and everything the agent's **data fields** collected are written on the caller's record, as a call where the CRM has calls and as a note otherwise. Collected values fill in the contact's name, email, phone, company or job title only where those are empty; nothing the CRM already holds is overwritten. A caller the CRM has never seen is created as a new contact (a lead in Salesforce and Zoho). Lokutor never deletes or merges anything in your CRM: the tools it may use are a fixed list per CRM, with no delete, merge or archive among them. CRM data given to the agent is marked as data, not instructions. Disconnecting (Integrations → **Disconnect**) removes the stored connection, and every agent on the account stops using the CRM. **Each call that uses your CRM costs \$0.04** from your balance, once per call ([Pricing and billing](/pricing)): a call on which the caller was looked up or identified, or that was logged. A web session with no `caller_phone` / `caller_email` that ends without a transcript never reaches the CRM and adds nothing. ### Transfer to a person (opt-in, phone calls) With **Transfer to a person** switched on (agent → Tools; `transfer_enabled: true` and `transfer_targets` in the agent's config), the agent on a phone call is offered `transfer_call` `{ "reason", "summary" }`. It uses it when the caller asks for a person or when it cannot resolve what they need. The caller is put through to the numbers you set, one after another; the person who answers hears the summary first. If nobody answers, the agent is told so and offers to take a message. It runs server-side: you do not register or answer it. Setup, what the caller hears, pricing and every config key: [Transfer calls to a person](/guides/call-transfer). ### Earlier calls (always on, not a tool) On a phone call, and on a web session that passes `caller_phone`, the agent is told before its first words what your account's earlier calls with that number left behind: how many there were and when, the last call's summary, and what its **data fields** collected. It greets a returning caller by name and confirms what it already has instead of asking again; if the caller says something different now, what they say now wins. When a call leaves a data field empty that an earlier call filled, the call's collected data keeps the earlier value, and the dashboard marks it as coming from an earlier call. Only the fields the agent itself collects are carried over. ### Date and time (always on, not a tool) Every dashboard agent (any session with an `agent_id`) knows the current date and time. They are written into its instructions when the call starts, in the agent's **timezone** (agent → Tools → Built-in; `timezone` in the agent's config, an IANA name such as `America/Mexico_City`; default `Europe/Madrid`). So "tomorrow at ten" or "are you open now" needs no tool call and adds no latency. A session without an `agent_id`, which sets its own prompt through the SDK, gets nothing added. If you need the date there, put it in your prompt. ## Best practices * **Keep it fast**: tool handlers should return within a few seconds. Slow tools leave the agent in a "thinking" state. * **Clear descriptions**: the model relies on `description` to decide when to use a tool. * **Handle errors**: return an error message as the result; the agent tells the user. * **Answer every call**: a `tool_call` without a `tool_result` leaves the agent waiting. ## Raw WebSocket protocol Send tools after connecting: ```json theme={null} { "type": "tools", "data": [{ "type": "function", "function": { "name": "get_time", "description": "Current time", "parameters": { "type": "object", "properties": {} } } }] } ``` Server notifies on tool execution: ```json theme={null} { "type": "tool_call", "name": "get_time", "arguments": "{}", "call_id": "..." } ``` Submit results: ```json theme={null} { "type": "tool_result", "data": { "call_id": "...", "result": "..." } } ``` # Text-to-Speech Source: https://docs.lokutor.com/sdk/tts Stream synthesized speech with TTSClient.synthesize(): options, defaults, the promise that resolves at end of stream and rejects with LokutorError, and Node.js, browser and Python examples `TTSClient` opens a WebSocket to `/ws/tts`, sends your text, and hands you audio chunks as they are generated. In JavaScript, `synthesize()` returns a promise that **resolves when the server has sent all the audio** and **rejects with a `LokutorError`** if the server returns an error or the stream stalls. ## Basic usage > [tab] Node.js (save to file) > > Node.js 22 or later. > > ```typescript theme={null} > import { TTSClient, VoiceStyle, Language } from '@lokutor/sdk'; > import fs from 'node:fs'; > > const client = new TTSClient({ apiKey: process.env.LOKUTOR_API_KEY! }); > const chunks: Buffer[] = []; > > await client.synthesize({ > text: 'Hello, this is Lokutor speaking.', > voice: VoiceStyle.F1, > language: Language.ENGLISH, > onAudio: (data) => chunks.push(Buffer.from(data)), > onTTFB: (ms) => console.log(`first audio after ${Math.round(ms)} ms`), > }); > > fs.writeFileSync('output.raw', Buffer.concat(chunks)); > // Convert: ffmpeg -f s16le -ar 44100 -ac 1 -i output.raw output.wav > ``` > [tab] Browser > > Pass a short-lived ticket from your backend, never your API key ([Secure browser setup](/guides/secure-browser-setup)). > > ```typescript theme={null} > import { TTSClient, VoiceStyle, Language } from '@lokutor/sdk'; > > const { ticket } = await fetch('/api/lokutor-ticket', { method: 'POST' }).then((r) => r.json()); > const client = new TTSClient({ apiKey: ticket }); > > const audioCtx = new AudioContext(); // inside a click handler > let nextTime = audioCtx.currentTime; > > await client.synthesize({ > text: 'Hello, this is Lokutor speaking.', > voice: VoiceStyle.F1, > language: Language.ENGLISH, > onAudio: (pcm16) => { > const int16 = new Int16Array(pcm16.buffer, pcm16.byteOffset, pcm16.byteLength / 2); > const float32 = new Float32Array(int16.length); > for (let i = 0; i < int16.length; i++) float32[i] = int16[i] / 32768; > > const buffer = audioCtx.createBuffer(1, float32.length, 44100); > buffer.getChannelData(0).set(float32); > > const source = audioCtx.createBufferSource(); > source.buffer = buffer; > source.connect(audioCtx.destination); > > const start = Math.max(audioCtx.currentTime, nextTime); > source.start(start); > nextTime = start + buffer.duration; > }, > }); > ``` > [tab] Python > > `play=True` needs `pip install "lokutor[audio]"`; with `play=False`, collect the audio in `on_audio`. > > ```python theme={null} > import os > from lokutor import TTSClient, VoiceStyle, Language > > client = TTSClient(api_key=os.environ["LOKUTOR_API_KEY"]) > > client.synthesize( > text="Hello, this is Lokutor speaking.", > voice=VoiceStyle.F1, > language=Language.ENGLISH, > play=True, > block=True, > ) > ``` ## Options | Option | Type | Default | Description | | :- | :- | :- | :- | | `text` | `string` | **required** | Text to synthesize. At most 5,000 characters. | | `voice` | `VoiceStyle` or a string id | `F1` | Voice slot or `clone_…` id. The speaker depends on `language` ([Voices](/voices-languages-models#voices)). | | `language` | `Language` | `ENGLISH` | Language. (Python also accepts a plain string such as `"es"`.) | | `speed` | `number` | not sent | Sent only if you set it. Accepted for compatibility; no effect on versa-2.0. | | `steps` | `number` | not sent | Sent only if you set it. Accepted for compatibility; no effect on versa-2.0. | | `visemes` | `boolean` | `false` | Lip-sync data. Not available on the current model ([Visemes](/sdk/visemes)). | | `onAudio` | `(Uint8Array) => void` | — | Called with each audio chunk | | `onTTFB` | `(ms: number) => void` | — | Time from sending the request to the first audio | | `onError` | `(error) => void` | — | Called with the same error the promise rejects with | The Python client sends `speed` and `steps` on every request (defaults `1.05` and `24`); they have no effect. ## Completion and errors (JavaScript) * The promise resolves when the server signals the end of the stream (`EOS`). * It rejects with a `LokutorError` carrying the server's code (for example `validation.invalid_voice` or `tts.synthesis_failed`) when the server sends an error frame. * It rejects with `internal.timeout` when no audio arrives within 30 seconds, or no further chunk within 15 seconds. * It rejects if the socket closes before the end of the stream, unless audio had arrived and the close was clean. ```typescript theme={null} try { await client.synthesize({ text, voice: VoiceStyle.F1, language: Language.ENGLISH, onAudio }); } catch (err) { console.error(err.code, err.message, err.retryable); } ``` Each call opens its own WebSocket. To send many short requests over one connection, use the [WebSocket API](/api-reference/streaming) directly. ## Audio format | Property | Value | | :- | :- | | Format | Signed 16-bit PCM, little-endian | | Sample rate | 44.1 kHz | | Channels | 1 (mono) | # Visemes (not available) Source: https://docs.lokutor.com/sdk/visemes Viseme (lip-sync) data: not available on the current model versa-2.0, which sends none. The request flag, the message format and a mouth-shape mapping are kept for a future model. > [!WARNING] > > **Not available on the current speech model.** Versa 2.0, which serves all synthesis today, produces > no viseme data: it generates audio from a latent representation and exposes nothing phoneme-aligned > to derive mouth shapes from. Setting `visemes: true` is accepted and simply yields no viseme events, > so lip-sync animation driven by this API will not move. > > The API is documented and kept in place because it is unchanged and will start returning data again > if a future model can supply it. If you are building an avatar today, drive it from audio amplitude > instead. The rest of this page describes the format the API used for viseme data, for when a model supplies it again. None of it produces anything on `versa-2.0`. ## Enable visemes **Voice Agent:** ```typescript theme={null} const client = new VoiceAgentClient({ auth: getTicket, prompt: 'You are helpful.', visemes: true, }); client.on('visemes', (visemes) => { console.log('Received', visemes.length, 'visemes'); }); ``` **TTS:** ```typescript theme={null} await client.synthesize({ text: 'Hello world', visemes: true, onVisemes: (visemes) => { console.log('Visemes:', visemes); }, }); ``` ## Viseme format ```typescript theme={null} interface Viseme { v: number; // Character index in source text c: string; // Normalized character/phoneme t: number; // Timestamp in seconds from audio start } ``` ## Character-to-mouth mapping | Char | Shape | | :- | :- | | `a` | Open wide | | `e`, `i` | Open medium | | `o`, `u` | Open round | | `m`, `p`, `b` | Lips together | | `f`, `v` | Lip bite | | `t`, `d`, `s`, `z` | Teeth close | | `l` | Tongue up | | `n`, `r` | Small opening | | `k`, `g` | Back throat | | `sil` | Closed | ## Basic implementation ```typescript theme={null} let timeline: Viseme[] = []; client.on('visemes', (visemes) => { timeline.push(...visemes); timeline.sort((a, b) => a.t - b.t); }); function updateMouth() { const now = audioContext.currentTime; let active = timeline[0]; for (const v of timeline) { if (v.t <= now) active = v; else break; } setMouthShape(mouthShapes[active?.c || 'sil'] || 'closed'); requestAnimationFrame(updateMouth); } ``` ## Smooth transitions ```typescript theme={null} const speed = 0.15; currentWeight[shape] += (targetWeight[shape] - currentWeight[shape]) * speed; ``` ## Handling interruptions ```typescript theme={null} client.on('status', (status) => { if (status === 'interrupted') timeline = []; // timeline is declared with let above }); ``` ## Timing Use `audioContext.currentTime`, not `Date.now()`. Viseme timestamps are offsets in seconds from the start of the audio. ## Driving an avatar today Until viseme data returns, animate the mouth from the agent's audio: compute the loudness of each `audio` chunk and open the mouth in proportion, timed against when the chunk plays. ```typescript theme={null} client.on('audio', (chunk: Uint8Array) => { const pcm = new Int16Array(chunk.buffer, chunk.byteOffset, chunk.byteLength / 2); let sum = 0; for (const s of pcm) sum += (s / 32768) ** 2; const level = Math.sqrt(sum / pcm.length); // 0–1; schedule it for this chunk's play time queueMouthOpening(level); }); ``` # JavaScript API Reference Source: https://docs.lokutor.com/sdks/javascript/reference Reference for @lokutor/sdk 1.6.0: VoiceAgentClient (auth, agentId, events, methods), TTSClient, STTClient, SpeechToTextClient, audio managers, enums, types, LokutorError and error codes. Browsers and Node.js 22+. Version 1.6.0. Install with `npm install @lokutor/sdk`. Runs in browsers and in Node.js 22 or later (it uses the global `WebSocket`). ## `VoiceAgentClient` The main class for real-time voice conversations. Manages the WebSocket connection, audio pipeline, conversation state, and event dispatching. ### Constructor ```typescript theme={null} new VoiceAgentClient(config: { apiKey?: string; auth?: () => string | Promise; agentId?: string; prompt?: string; voice?: VoiceStyle | string; language?: Language | 'auto' | ''; visemes?: boolean; enableAudio?: boolean; serverUrl?: string; tools?: ToolDefinition[]; onTranscription?: (text: string) => void; onResponse?: (text: string) => void; onVisemes?: (visemes: Viseme[]) => void; onStatus?: (status: string) => void; onError?: (error: any) => void; }) ``` #### Config Options | Option | Type | Required | Default | Description | | :- | :- | :- | :- | :- | | `apiKey` | `string` | Unless `auth` is set | — | An API key (server-side only) or a `wst_` ticket. Sent as the `api_key` query parameter. | | `auth` | `() => string \| Promise` | No | — | Called before every connect and reconnect; its result is used as the credential. In a browser, fetch a fresh ticket from your backend here ([Secure browser setup](/guides/secure-browser-setup)). | | `agentId` | `string` | No | — | Run one of your dashboard agents. Then `prompt`, `voice` and `language` are sent only if you set them, as overrides. | | `prompt` | `string` | Unless `agentId` is set | — | System prompt for the language model. | | `voice` | `VoiceStyle` or string id | No | `F1` | Voice slot or `clone_…` id ([Voices](/voices-languages-models#voices)). | | `language` | `Language`, `'auto'` or `''` | No | `ENGLISH` | Conversation language. Affects STT and TTS. `'auto'` (or `''`, since 1.9.0) lets the agent follow the caller's language: it is detected from what they say and the agent replies in it ([Voice chat](/api-reference/voice-chat)). The agent can speak all nine [languages](/voices-languages-models#languages) but only understands six of them ([which](/voices-languages-models#which-languages-are-understood)). | | `visemes` | `boolean` | No | `false` | Request lip-sync metadata. **Produces nothing on the current speech model** — see [Visemes](/sdk/visemes). | | `enableAudio` | `boolean` | No | `false` | Automatically manage microphone and speaker in browser. | | `serverUrl` | `string` | No | `wss://api.lokutor.com/ws/agent` | Custom WebSocket endpoint. Use for local development or proxies. | | `tools` | `ToolDefinition[]` | No | `[]` | OpenAI-format tool definitions for LLM function calling. | | `onTranscription` | `(text: string) => void` | No | — | Called with each final line of user speech. | | `onResponse` | `(text: string) => void` | No | — | Called when the agent generates a text response. | | `onVisemes` | `(visemes: Viseme[]) => void` | No | — | Called when viseme metadata arrives. | | `onStatus` | `(status: string) => void` | No | — | Called on state transitions. | | `onError` | `(error: LokutorError) => void` | No | — | Called on connection, protocol and server errors. | Constructor callbacks fire once per event, alongside any listeners registered with `on()` for the same event. They are constructor options only: assigning `client.onError = …` later does not work (the field is private). ### Methods #### `connect(customAudioManager?: AudioManager): Promise` Opens a WebSocket connection to the voice agent server. * If `enableAudio` is true (or `customAudioManager` is provided), initializes the audio pipeline. * Calls `auth` first, if set, for the credential. * Sends configuration messages immediately after `onopen`, in this order: `voice`, `language`, `tools` (only if any are set), `visemes`, `prompt`, `rates`. With `agentId`, `voice`, `language` and `prompt` are sent only if you set them. * Starts the microphone if audio management is enabled. * Returns `true` on successful connection. * Rejects with a `LokutorError` if the connection fails (invalid credential, network error, a refused handshake) or the microphone cannot start (`audio.microphone_unavailable`). ```typescript theme={null} const connected = await client.connect(); if (connected) { console.log('Connected'); } ``` #### `startManaged(config?: { audioManager?: AudioManager }): Promise` The "Golden Path." Enables audio management automatically and connects. * Sets `enableAudio = true`. * Creates a `BrowserAudioManager` if in a browser. * Throws if called outside a browser without a custom `AudioManager`. * Returns the client instance for chaining. ```typescript theme={null} await client.startManaged(); ``` > Must be called inside a user gesture in browsers (e.g., button click). #### `sendAudio(audioData: Uint8Array): void` Sends raw PCM16 audio data to the server. * Format: Int16 PCM, little-endian, 16 kHz, mono * Chunk size: \~320 bytes (20 ms) * Silently ignored if the WebSocket is not open. ```typescript theme={null} const pcmData = new Uint8Array(320); // 20ms of 16kHz mono PCM client.sendAudio(pcmData); ``` #### `disconnect(): void` Closes the WebSocket connection and releases all resources. * Sets `isUserDisconnect = true` to prevent auto-reconnection. * Stops microphone and playback. * Cleans up the audio manager. ```typescript theme={null} client.disconnect(); ``` #### `toggleMute(): boolean` Toggles the microphone mute state. * Returns the new mute state (`true` = muted). * No-op if no audio manager is attached. ```typescript theme={null} const isMuted = client.toggleMute(); console.log('Muted:', isMuted); ``` #### `getAmplitude(): number` Returns the current microphone amplitude. * Range: `0` to `1` * Useful for driving VU meters or visualization. * Returns `0` if no audio manager is attached. ```typescript theme={null} const volume = client.getAmplitude(); document.getElementById('vu-meter').style.width = `${volume * 100}%`; ``` #### `updatePrompt(newPrompt: string): void` Updates the system prompt mid-conversation. ```typescript theme={null} client.updatePrompt('You are now a pirate. Speak like one.'); ``` #### `updateVoice(voice: VoiceStyle): void` Changes the voice mid-conversation. ```typescript theme={null} client.updateVoice(VoiceStyle.M2); ``` #### `updateLanguage(language: Language | 'auto' | ''): void` Changes the language mid-conversation. `'auto'` (or `''`) switches to following the caller. ```typescript theme={null} client.updateLanguage(Language.SPANISH); ``` #### `updateTools(tools: ToolDefinition[]): void` Replaces the tool definitions mid-conversation. ```typescript theme={null} client.updateTools([{ type: 'function', function: { name: 'get_weather', ... } }]); ``` #### `submitToolResult(callId: string, result: string | object): void` Submits the result of a tool execution back to the LLM. ```typescript theme={null} client.on('tool_call', ({ call_id, name, arguments: args }) => { const result = myTool(name, JSON.parse(args)); client.submitToolResult(call_id, result); }); ``` #### `getTranscript(): Array<{ role: 'user' | 'agent'; text: string; timestamp: number }>` Returns the conversation history: final user lines and agent replies. Partial transcripts are not stored. * Each entry includes the speaker role, text, and a timestamp (`performance.now()` milliseconds where available). * Returns a shallow copy; modifying the array does not affect internal state. ```typescript theme={null} const history = client.getTranscript(); history.forEach(msg => { console.log(`${msg.role}: ${msg.text}`); }); ``` #### `getTranscriptText(): string` Returns the conversation as a formatted text string. ```typescript theme={null} const text = client.getTranscriptText(); // You: Hello // Agent: Hi there! ``` #### `on(event: string, callback: Function): this` Subscribes to an event. Chainable. Supported events: | Event | Payload | When | | :- | :- | :- | | `transcription` | `string` | A final line of user speech | | `transcription_partial` | `string` | Interim user text while they speak (not stored in `getTranscript()`) | | `response` | `string` | An agent reply | | `audio` | `Uint8Array` | Agent audio, Int16 PCM 44.1 kHz mono | | `visemes` | `Viseme[]` | Not sent on the current model | | `status` | `string` | `connected`, `listening`, `thinking`, `speaking`, `interrupted`, config acks, and the client-only `reconnecting` / `disconnected` | | `error` | `LokutorError` | Any error. Also delivered to `onError` | | `tool_call` | `{ name, arguments, call_id }` | Once per tool call; answer with `submitToolResult(call_id, result)` | | `reconnected` | — | A dropped connection was re-established | | `ended` | `{ code, reason }` | The server ended the session on purpose; no reconnection follows | | `session_limit` | `{ seconds, reason }` | The session's remaining time, when it has a limit (key-less demo only) | ```typescript theme={null} client .on('transcription', (text) => console.log('User:', text)) .on('response', (text) => console.log('Agent:', text)) .on('audio', (data) => playAudio(data)); ``` #### `onAudio(callback: (data: Uint8Array) => void): void` Convenience method equivalent to `on('audio', callback)`. #### `onVisemes(callback: (visemes: Viseme[]) => void): void` Convenience method equivalent to `on('visemes', callback)`. ### Properties | Property | Type | Description | | :- | :- | :- | | `prompt` | `string` | Current system prompt | | `voice` | `VoiceStyle` | Current voice style | | `language` | `Language` or `''` | Current language; `''` when the agent follows the caller | | `tools` | `ToolDefinition[]` | Registered tool definitions | | `connected` | `boolean` | Whether the WebSocket is currently open | | `generation` | `number` | Current utterance generation counter | ### Static Discovery Methods The discovery endpoints are public (no API key). The methods call `https://api.lokutor.com` (or the origin of `baseUrl`). | Method | Returns | Description | | :- | :- | :- | | `VoiceAgentClient.fetchVoices(baseUrl?)` | `Promise` | Available voice styles | | `VoiceAgentClient.fetchLanguages(baseUrl?)` | `Promise` | Supported languages | | `VoiceAgentClient.fetchModels(baseUrl?)` | `Promise` | Loaded TTS model versions | | `VoiceAgentClient.fetchConfig(baseUrl?)` | `Promise` | Server limits and defaults | | `VoiceAgentClient.fetchStatus(baseUrl?)` | `Promise` | Rich runtime status | | `VoiceAgentClient.fetchHealth(baseUrl?)` | `Promise` | Readiness, from `GET /ready` (`{ ready, status }`) | ```typescript theme={null} const voices = await VoiceAgentClient.fetchVoices(); const config = await VoiceAgentClient.fetchConfig(); console.log('Max text length:', config.max_text_length); // Another server const local = await VoiceAgentClient.fetchVoices('http://localhost:8080'); ``` ## `TTSClient` Standalone client for text-to-speech synthesis without the conversational agent. ### Constructor ```typescript theme={null} new TTSClient(config: { apiKey: string }) ``` `apiKey` is an API key, or in a browser a `wst_` ticket. ### Methods #### `synthesize(options): Promise` Opens a WebSocket to `/ws/tts`, sends the request, and streams back audio. ```typescript theme={null} await client.synthesize({ text: 'Hello world', voice: VoiceStyle.F1, language: Language.ENGLISH, onAudio: (data) => playAudio(data), onTTFB: (ms) => console.log(`TTFB: ${ms}ms`), }); ``` #### SynthesizeOptions | Option | Type | Required | Default | Description | | :- | :- | :- | :- | :- | | `text` | `string` | Yes | — | Text to synthesize | | `voice` | `VoiceStyle` or string id | No | `F1` | Voice slot or `clone_…` id | | `language` | `Language` | No | `ENGLISH` | Language | | `speed` | `number` | No | not sent | Sent only if set. Accepted for compatibility; no effect on versa-2.0. | | `steps` | `number` | No | not sent | Sent only if set. Accepted for compatibility; no effect on versa-2.0. | | `visemes` | `boolean` | No | `false` | Not available on the current model | | `onAudio` | `(data: Uint8Array) => void` | No | — | Audio chunk callback | | `onVisemes` | `(visemes: Viseme[]) => void` | No | — | Viseme callback | | `onTTFB` | `(ms: number) => void` | No | — | Time-to-first-byte callback | | `onError` | `(error: any) => void` | No | — | Called with the same error the promise rejects with | The promise **resolves** when the server signals the end of the stream (`EOS`). It **rejects** with a `LokutorError` when the server sends an error frame (with the server's code), with `internal.timeout` when no audio arrives within 30 s or no further chunk within 15 s, and when the socket closes before the end of the stream (unless audio had arrived and the close was clean). ## `STTClient` Standalone client for one-shot transcription of a complete, pre-recorded audio clip. See [Speech-to-Text](/sdk/stt) for the full guide. ### Constructor ```typescript theme={null} new STTClient(config: { apiKey: string; serverUrl?: string }) ``` ### Methods #### `transcribe(options: TranscribeOptions): Promise` ```typescript theme={null} const result = await client.transcribe({ audio: fileBlobOrBuffer, language: Language.ENGLISH, }); console.log(result.text); ``` | Option | Type | Required | Default | Description | | :- | :- | :- | :- | :- | | `audio` | `Blob \| ArrayBuffer \| Uint8Array` | Yes | — | A `Blob` is uploaded as a WAV file; a buffer is sent as raw PCM16 (set `sampleRate`) | | `format` | `"wav" \| "pcm16"` | No | `"wav"` | Only needed for raw PCM16 input | | `sampleRate` | `number` | No | — | Required when `format` is `"pcm16"` | | `language` | `Language` | No | server default | ISO language code | Returns `TranscribeResult`: `{ text, latencyMs, engine, sampleRate, language, durationSeconds, segments? }`. ## `SpeechToTextClient` Standalone client for continuous/live transcription from a microphone, with server-side VAD detecting utterance boundaries. See [Speech-to-Text](/sdk/stt) for the full guide. ### Constructor ```typescript theme={null} new SpeechToTextClient(config: SpeechToTextOptions) ``` | Option | Type | Required | Default | Description | | :- | :- | :- | :- | :- | | `apiKey` | `string` | Yes | — | API key, or in a browser a `wst_` ticket | | `serverUrl` | `string` | No | `wss://api.lokutor.com/ws/stt` | — | | `language` | `Language` | No | `ENGLISH` | — | | `vad` | `"silero" \| "rms"` | No | `"silero"` | Sent, but ignored by the production recognition path | | `onPartialTranscript` | `(text: string) => void` | No | — | Fires repeatedly mid-utterance | | `onFinalTranscript` | `(text: string) => void` | No | — | Fires once the utterance ends | | `onError` | `(error: LokutorError) => void` | No | — | — | | `onStatusChange` | `(status) => void` | No | — | `"connecting" \| "connected" \| "disconnected"` | ### Methods #### `connect(customAudioManager?: AudioManager): Promise` Requests microphone access (or uses `customAudioManager`, e.g. `NodeAudioManager`) and starts streaming. Rejects with `audio.microphone_unavailable` if the microphone cannot start. #### `endUtterance(): void` Finalizes the utterance in progress **and ends the session**: the server sends the final transcript, then closes. Connect again to transcribe more. #### `disconnect(): void` Stops the microphone and closes the connection. ## `BrowserAudioManager` Manages the Web Audio API pipeline for browser environments. ### Constructor ```typescript theme={null} new BrowserAudioManager(config?: BrowserAudioConfig) ``` #### BrowserAudioConfig | Option | Type | Default | Description | | :- | :- | :- | :- | | `inputSampleRate` | `number` | `16000` | Target microphone sample rate | | `outputSampleRate` | `number` | `44100` | Speaker output sample rate | | `autoGainControl` | `boolean` | `true` | Enable AGC | | `echoCancellation` | `boolean` | `true` | Enable echo cancellation | | `noiseSuppression` | `boolean` | `true` | Enable noise suppression | | `keepAwake` | `boolean` | `true` | Keep the screen awake while the microphone is live (Screen Wake Lock) | | `microphone` | `MediaStream \| Promise` | — | A stream from `requestMicrophone()`, requested inside the tap that started the call; used instead of asking again when the connection opens | | `onInputError` | `(error: Error) => void` | — | Microphone error handler | #### requestMicrophone() ```typescript theme={null} requestMicrophone(constraints?: { autoGainControl?: boolean; echoCancellation?: boolean; noiseSuppression?: boolean }): Promise ``` Asks for the microphone immediately. Call it synchronously in the click or tap handler that starts a call, before any `await`, and pass the promise as `microphone`. iOS Safari reliably shows its permission prompt only for a request made inside a user gesture, and refuses capture outright while the page's audio session is in `'playback'` mode; this function moves that session back to `'auto'` first. ```typescript theme={null} button.onclick = () => { const microphone = requestMicrophone(); // inside the tap const client = new VoiceAgentClient({ auth: getTicket, prompt }); client.connect(new BrowserAudioManager({ microphone })) .catch((e) => { if (e.code === 'audio.microphone_unavailable') showMicHelp(e); }); }; ``` ### Methods | Method | Returns | Description | | :- | :- | :- | | `init()` | `Promise` | Initialize AudioContext | | `startMicrophone(onAudioInput)` | `Promise` | Begin capturing microphone | | `stopMicrophone()` | `void` | Stop microphone | | `playAudio(pcm16Data)` | `void` | Schedule audio for playback | | `stopPlayback()` | `void` | Stop all playing audio | | `setMuted(muted)` | `void` | Mute/unmute microphone | | `isMicMuted()` | `boolean` | Current mute state | | `getAmplitude()` | `number` | Current RMS amplitude (0-1) | | `getFrequencyData()` | `Uint8Array` | FFT data for visualization | | `getWaveformData()` | `Uint8Array` | Time-domain data for waveform | | `cleanup()` | `void` | Release resources | | `getState()` | `string \| null` | AudioContext state | | `isRecording()` | `boolean` | Whether mic is active | ## `NodeAudioManager` Node.js audio implementation using `speaker` and `node-record-lpcm16`. Pass it to `connect()` and the client starts the microphone and plays the agent's audio: ```typescript theme={null} import { VoiceAgentClient, NodeAudioManager } from '@lokutor/sdk'; const client = new VoiceAgentClient({ apiKey: process.env.LOKUTOR_API_KEY, prompt: 'You are helpful.' }); await client.connect(new NodeAudioManager()); ``` Dependencies must be installed separately: ```bash theme={null} npm install speaker node-record-lpcm16 ``` ## Enums ### `VoiceStyle` ```typescript theme={null} enum VoiceStyle { F1 = "F1", F2 = "F2", F3 = "F3", F4 = "F4", F5 = "F5", M1 = "M1", M2 = "M2", M3 = "M3", M4 = "M4", M5 = "M5", // also: EN_F1 … EN_M5 = "en_f1" … "en_m5", ESCA_F1 … ESCA_M5 = "esca_f1" … "esca_m5" } ``` Use `F1`–`M5`: they are the ids `GET /voices` returns, and each resolves to the native speaker of the session's `language` ([Voices](/voices-languages-models#voices)). In 1.6.0 the JSDoc marks them `@deprecated` in favour of the explicit `EN_*` / `ESCA_*` members, which pin one reference speaker whatever the language; the slot ids remain supported and are what these docs teach. Any `voice` field also accepts a plain string, such as a `clone_…` id. ### `Language` ```typescript theme={null} enum Language { ENGLISH = "en", SPANISH = "es", CATALAN = "ca", GALICIAN = "gl", BASQUE = "eu", PORTUGUESE = "pt", FRENCH = "fr", ITALIAN = "it", GERMAN = "de", } ``` ## Interfaces ### `Viseme` ```typescript theme={null} interface Viseme { v: number; // Character index in source text c: string; // Normalized character/phoneme t: number; // Timestamp in seconds from audio start } ``` The SDK receives `v`, `c`, `t` from the server and passes them through as-is. ### `ToolDefinition` ```typescript theme={null} interface ToolDefinition { type: 'function'; function: { name: string; description: string; parameters: { type: 'object'; properties: Record; required?: string[]; }; }; } ``` ### `ToolCall` ```typescript theme={null} interface ToolCall { name: string; arguments: string; // JSON string call_id: string; // Unique ID for this invocation } ``` ### `LokutorConfig` ```typescript theme={null} interface LokutorConfig { apiKey?: string; // optional when auth is given auth?: () => string | Promise; // called before every connect/reconnect agentId?: string; onTranscription?: (text: string) => void; onResponse?: (text: string) => void; onAudio?: (data: Uint8Array) => void; onStatus?: (status: string) => void; onError?: (error: any) => void; } ``` ### `SynthesizeOptions` ```typescript theme={null} interface SynthesizeOptions { text: string; voice?: VoiceStyle | string; language?: Language; speed?: number; steps?: number; visemes?: boolean; } ``` ### `BrowserAudioOptions` ```typescript theme={null} interface BrowserAudioOptions { inputSampleRate?: number; // Target mic rate (default 16000) outputSampleRate?: number; // Speaker rate (default 44100) autoGainControl?: boolean; // Enable AGC (default true) echoCancellation?: boolean; // Enable echo cancellation (default true) noiseSuppression?: boolean; // Enable noise suppression (default true) keepAwake?: boolean; // Keep the screen awake while the mic is live (default true) microphone?: MediaStream | Promise; // From requestMicrophone(), called in the tap analyserEnabled?: boolean; // Enable FFT/waveform analysis onInputError?: (error: Error) => void; } ``` ## Constants ### `AUDIO_CONFIG` ```typescript theme={null} const AUDIO_CONFIG = { SAMPLE_RATE: 16000, // Microphone input rate SAMPLE_RATE_INPUT: 16000, // Alias for SAMPLE_RATE SPEAKER_SAMPLE_RATE: 44100, // Agent audio output rate SAMPLE_RATE_OUTPUT: 44100, // Alias for SPEAKER_SAMPLE_RATE CHANNELS: 1, // Mono CHUNK_DURATION_MS: 20, // 20ms chunks CHUNK_SIZE: 320, // Computed: (16000 * 20) / 1000 }; ``` ### `DEFAULT_URLS` ```typescript theme={null} const DEFAULT_URLS = { VOICE_AGENT: "wss://api.lokutor.com/ws/agent", TTS: "wss://api.lokutor.com/ws/tts", STT: "wss://api.lokutor.com/ws/stt", }; ``` ## Utility Functions ### `pcm16ToFloat32(int16Data: Int16Array): Float32Array` Converts Int16 PCM to Float32 (-1.0 to 1.0). ### `float32ToPcm16(float32Data: Float32Array): Int16Array` Converts Float32 to Int16 PCM. Clamps to \[-1, 1] before conversion. ### `resample(input: Float32Array, inputRate: number, outputRate: number): Float32Array` Linear interpolation resampling. ### `resampleWithAntiAliasing(input: Float32Array, inputRate: number, outputRate: number): Float32Array` Resamples with a low-pass filter to prevent aliasing when downsampling. ### `normalizeAudio(data: Float32Array, targetPeak?: number): Float32Array` Normalizes audio to a target peak amplitude. ### `calculateRMS(data: Float32Array | Uint8Array): number` Calculates Root Mean Square amplitude. ### `StreamResampler` Stateful resampler for streaming audio chunks. The output does not depend on how the input is split into chunks. `BrowserAudioManager` uses it to bring the microphone down to 16 kHz. When downsampling it low-passes first (since 1.6.1). It uses a 63-tap windowed-sinc filter at 0.45 × the output rate (7.2 kHz for 16 kHz) and then linear interpolation, so sound above the output's Nyquist frequency does not fold back into the speech band. The filter delays the audio by 31 input samples (0.65 ms at 48 kHz). A flush ends the stream: it drains the filter, returns the remaining audio, and the resampler starts over. Upsampling uses linear interpolation. ```typescript theme={null} const resampler = new StreamResampler(48000, 16000); const output = resampler.process(chunk); const final = resampler.process(new Float32Array(0), true); // flush ``` ## Quick Helpers ### `simpleConversation(config)` One-liner to create and connect a `VoiceAgentClient`. ```typescript theme={null} const client = await simpleConversation({ apiKey: process.env.LOKUTOR_API_KEY, prompt: 'You are helpful.', }); ``` ### `simpleTTS(options)` One-liner for TTS synthesis. ```typescript theme={null} await simpleTTS({ apiKey: process.env.LOKUTOR_API_KEY, text: 'Hello world', onAudio: (data) => playAudio(data), }); ``` ## Error Handling ### `LokutorError` All SDK errors are instances of `LokutorError`: ```typescript theme={null} class LokutorError extends Error { code: ErrorCode; message: string; detail?: string; retryable: boolean; original?: unknown; } ``` | Property | Type | Description | | :- | :- | :- | | `code` | `ErrorCode` | Machine-readable error identifier (e.g. `auth.invalid_key`) | | `message` | `string` | Human-readable description | | `detail` | `string` | Additional context (may contain internal data) | | `retryable` | `boolean` | Whether the client should retry | | `original` | `unknown` | Original underlying error, if any | ### `isRetryable(error: unknown): boolean` Returns `true` if the error is a retryable `LokutorError`: ```typescript theme={null} import { isRetryable } from '@lokutor/sdk'; client.on('error', (error) => { if (isRetryable(error)) { console.warn('Will retry:', error.code); } else { console.error('Fatal:', error.message); } }); ``` ### Error Codes `ErrorCode` includes every server code in the [Error Catalog](/api-reference/errors) (among them `billing.insufficient_balance`, `billing.topup_required`, `billing.limit_reached`, `billing.account_disputed` and `agent.not_found`) plus the client-side `session.ended`, `audio.microphone_unavailable` and `ws.close`. `retryable` is `false` for authentication, validation, billing, `agent.not_found`, `session.ended` and `audio.microphone_unavailable`. See [Error handling](/guides/error-handling) for a recipe. ### Debug Tracing Enable debug tracing by setting `window.LOKUTOR_TRACE = true` or `localStorage.setItem('lokutorTrace', '1')`. ## Related Pages * [TTS Guide](/sdk/tts) * [Agent Guide](/sdk/agent) * [Discovery Guide](/sdk/discovery) * [Secure browser setup](/guides/secure-browser-setup) * [Viseme Guide](/sdk/visemes) * [WebSocket Protocol](/guides/websocket-protocol) * [Tool Calling](/sdk/tool-calling) # Python SDK Source: https://docs.lokutor.com/sdks/python/introduction The lokutor Python package 1.5.0: what it covers, installing it on Python 3.8+ (pip install lokutor, plus lokutor[audio] and PortAudio for local playback and recording), and where the examples are. The official Python SDK for Lokutor: text-to-speech, transcription and full-duplex voice agents over the same API as the [JavaScript SDK](/sdks/javascript/reference), with the same class names. ## What it covers * **`TTSClient`**: stream speech from text, play it locally or collect the PCM. * **`STTClient`** and **`SpeechToTextClient`**: transcribe a recorded clip, or a live microphone. * **`VoiceAgentClient`**: a conversation with an agent through your microphone and speakers, with [tool calling](/sdk/tool-calling). * **Languages**: speech in English, Spanish, Catalan, Galician, Basque, Portuguese, French, Italian, German, Dutch, Polish, Romanian and Russian; recognition in the first nine, with one model (Dutch, Polish, Romanian and Russian are speak-only). * **`lokutor.audio_utils`**: PCM/float conversion, resampling (with anti-aliasing), streaming resampling and RMS helpers. ## Installation Python 3.8 or later. ```bash theme={null} pip install lokutor ``` That is enough to call the API: synthesize to bytes, transcribe files. To play or record audio on the local machine (`play=True`, `start_conversation()`, `SpeechToTextClient.start()`), add the audio extra. It needs the PortAudio library first: ```bash theme={null} brew install portaudio # macOS sudo apt install portaudio19-dev # Debian / Ubuntu pip install "lokutor[audio]" ``` ## Next * [Python Quickstart](/sdks/python/quickstart) * [Python API Reference](/sdks/python/reference) * Examples: [`python/examples`](https://github.com/lokutor-ai/lokutor-sdk/tree/main/python/examples) in the SDK repository (`simple_tts.py`, `simple_chat.py`, `advanced_chat.py`) # Python Quickstart Source: https://docs.lokutor.com/sdks/python/quickstart Python quickstart: install lokutor, synthesize speech to a WAV file or the speakers, run a voice agent through the microphone, register callbacks, and handle tool calls. ## Installation Python 3.8 or later. ```bash theme={null} pip install "lokutor[audio]" # includes PyAudio for the speakers and microphone used below ``` PyAudio needs PortAudio: `brew install portaudio` (macOS) or `sudo apt install portaudio19-dev` (Debian/Ubuntu). Without local audio, `pip install lokutor` is enough. ```bash theme={null} export LOKUTOR_API_KEY=sk_your_key_here ``` ## TTS to a WAV file ```python theme={null} import os import wave from lokutor import TTSClient, VoiceStyle, Language client = TTSClient(api_key=os.environ["LOKUTOR_API_KEY"]) chunks = [] client.synthesize( text="Hello from Lokutor.", voice=VoiceStyle.F1, language=Language.ENGLISH, on_audio=chunks.append, play=False, block=True, ) with wave.open("hello.wav", "wb") as f: f.setnchannels(1) f.setsampwidth(2) f.setframerate(44100) f.writeframes(b"".join(chunks)) ``` Use `play=True` instead to hear it through your speakers. ## Voice Agent ```python theme={null} from lokutor import VoiceAgentClient, VoiceStyle, Language import os client = VoiceAgentClient( api_key=os.environ['LOKUTOR_API_KEY'], prompt="You are a helpful assistant.", voice=VoiceStyle.F1, language=Language.ENGLISH, ) client.start_conversation() # talk through your microphone; Ctrl+C to stop ``` ## Events `client.on(event, callback)` registers a callback directly — it is **not** a decorator (it takes the callback as its second argument and returns the client, not a decorator function), so `@client.on('transcription')` above a `def` will raise a `TypeError`. Call it like this instead: ```python theme={null} def on_transcription(text): print(f"You: {text}") def on_response(text): print(f"Agent: {text}") def on_status(status): print(f"Status: {status}") client.on('transcription', on_transcription) client.on('response', on_response) client.on('status', on_status) ``` Or, equivalently, pass the callbacks directly into the constructor as `on_transcription=`, `on_response=`, `on_status=`, etc. — see the [Python API Reference](/sdks/python/reference). ## Transcript ```python theme={null} history = client.get_transcript() text = client.get_transcript_text() ``` ## Dynamic prompts ```python theme={null} client.update_prompt("You are now a technical expert.") ``` ## Tool calls ```python theme={null} def on_tool_call(name, arguments, call_id): # arguments is a JSON string client.submit_tool_result(call_id, {"ok": True}) client.on('tool_call', on_tool_call) ``` Register the tools themselves with `tools=[...]` in the constructor ([Tool Calling](/sdk/tool-calling)). # Python API Reference Source: https://docs.lokutor.com/sdks/python/reference Reference for the lokutor Python package 1.5.0 (Python 3.8+): VoiceAgentClient, TTSClient, STTClient, SpeechToTextClient, callbacks including on_tool_call(name, arguments, call_id), enums and helpers Version 1.5.0, Python 3.8 or later. `pip install lokutor` for API use; `pip install "lokutor[audio]"` (needs PortAudio: `brew install portaudio` or `sudo apt install portaudio19-dev`) to play or record on the local machine. Every `voice` and `language` argument also accepts a plain string (`"F1"`, `"es"`). ## `VoiceAgentClient` ### Constructor ```python theme={null} client = VoiceAgentClient( api_key: str, prompt: str = "You are a helpful AI assistant", voice: VoiceStyle = VoiceStyle.F1, language: Language = Language.ENGLISH, visemes: bool = False, tools: List[Dict] = None, on_transcription: Callable[[str], None] = None, on_response: Callable[[str], None] = None, on_audio: Callable[[bytes], None] = None, on_visemes: Callable[[list], None] = None, on_tool_call: Callable[[str, str, str], None] = None, # (name, arguments, call_id) on_status: Callable[[str], None] = None, on_error: Callable[[str], None] = None, ) ``` ### Events | Event | Callback | Description | | :- | :- | :- | | `transcription` | `(text)` | User speech | | `response` | `(text)` | Agent text response | | `audio` | `(data: bytes)` | Raw PCM audio | | `visemes` | `(visemes: List[Viseme])` | Lip-sync data | | `status` | `(status: str)` | State changes | | `tool_call` | `(name, arguments, call_id)` | The model called one of your tools. `arguments` is a JSON string; answer with `submit_tool_result(call_id, result)` | | `error` | `(error)` | A server error frame's `data` (a dict or a string), or a connection error message | Register listeners with `.on(event, callback)`: ```python theme={null} client.on('transcription', lambda text: print(f"You: {text}")) ``` ### Methods | Method | Description | | :- | :- | | `start_conversation()` | Start a full-duplex conversation through the local microphone and speakers (needs `lokutor[audio]`); blocks until interrupted | | `connect()` | Open WebSocket connection | | `disconnect()` | Close connection | | `update_prompt(new_prompt)` | Update system prompt mid-session | | `submit_tool_result(call_id, result)` | Return a tool's result (`str` or `dict`) | | `get_transcript()` | Return conversation history | | `get_transcript_text()` | Return formatted transcript | ## `TTSClient` ### Constructor ```python theme={null} client = TTSClient(api_key: str) ``` ### Methods | Method | Description | | :- | :- | | `synthesize(text, voice, language, speed, steps, visemes, on_audio, on_visemes, on_ttfb, play, block)` | Synthesize speech from text | ### `synthesize` parameters | Param | Type | Default | Description | | :- | :- | :- | :- | | `text` | `str` | — | Text to synthesize | | `voice` | `VoiceStyle` | `F1` | Voice | | `language` | `Language` | `ENGLISH` | Language | | `speed` | `float` | `1.05` | Always sent. Accepted for compatibility; no effect on versa-2.0. | | `steps` | `int` | `24` | Always sent. Accepted for compatibility; no effect on versa-2.0. | | `visemes` | `bool` | `False` | Not available on the current model ([Visemes](/sdk/visemes)) | | `on_audio` | `Callable[[bytes], None]` | `None` | Called with each Int16 PCM chunk (44.1 kHz mono) | | `on_ttfb` | `Callable[[float], None]` | `None` | Milliseconds to the first audio | | `play` | `bool` | `True` | Play through the local speakers (needs `lokutor[audio]`). Use `False` to only collect audio | | `block` | `bool` | `True` | Wait until the stream ends (and playback finishes, if `play`), up to 30 s | ## `STTClient` Standalone client for one-shot transcription of a complete, pre-recorded audio clip. See [Speech-to-Text](/sdk/stt) for the full guide. ### Constructor ```python theme={null} client = STTClient(api_key: str, server_url: str = DEFAULT_STT_URL) ``` ### Methods | Method | Description | | :- | :- | | `transcribe(audio, format, sample_rate, language, timeout)` | Transcribe a complete audio clip, returns a `dict` | ### `transcribe` parameters | Param | Type | Default | Description | | :- | :- | :- | :- | | `audio` | `bytes` | — | Raw audio bytes — a full WAV file (`format="wav"`) or raw PCM16 (`format="pcm16"`) | | `format` | `str` | `"wav"` | `"wav"` or `"pcm16"` | | `sample_rate` | `int` | `None` | Required when `format="pcm16"` | | `language` | `Language` | `None` | ISO language code | | `timeout` | `float` | `30.0` | Request timeout in seconds | Returns a `dict` with keys `text`, `latency_ms`, `engine`, `sample_rate`, `language`, `duration_seconds`, and optionally `segments`. ## `SpeechToTextClient` Standalone client for continuous/live transcription from a microphone, with server-side VAD detecting utterance boundaries. See [Speech-to-Text](/sdk/stt) for the full guide. ### Constructor ```python theme={null} client = SpeechToTextClient( api_key: str, server_url: str = DEFAULT_STT_URL, language: Language = Language.ENGLISH, vad: str = "silero", on_partial_transcript: Callable[[str], None] = None, on_final_transcript: Callable[[str], None] = None, on_error: Callable[[str], None] = None, ) ``` ### Methods | Method | Description | | :- | :- | | `start()` | Connect and start streaming microphone audio (non-blocking; needs `lokutor[audio]`) | | `end_utterance()` | Finalize the utterance in progress and end the session | | `stop()` | Stop the microphone and close the connection | ## Enums ### `VoiceStyle` `F1`–`F5` (female), `M1`–`M5` (male): the voice slots `GET /voices` returns. Each resolves to the native speaker of the session's language ([Voices](/voices-languages-models#voices)). The enum also has explicit `EN_*` and `ESCA_*` members, which pin one reference speaker. ### `Language` `ENGLISH`, `SPANISH`, `CATALAN`, `GALICIAN`, `BASQUE`, `PORTUGUESE`, `FRENCH`, `ITALIAN`, `GERMAN` ## Data structures ### `Viseme` ```python theme={null} @dataclass class Viseme: id: int # Character index (maps from server field `v`) char: str # Normalized character (maps from server field `c`) timestamp: float # Seconds from audio start (maps from server field `t`) ``` ## Audio utilities `lokutor.audio_utils` provides: * `pcm16_to_float32` / `float32_to_pcm16` * `resample` / `resample_with_anti_aliasing` * `calculate_rms` * `StreamResampler` — for streaming scenarios ## Convenience functions ```python theme={null} import os from lokutor import simple_conversation, simple_tts, simple_transcribe, VoiceStyle api_key = os.environ["LOKUTOR_API_KEY"] simple_tts("Hello world", api_key, voice=VoiceStyle.F1) # plays locally: needs lokutor[audio] simple_conversation(api_key, prompt="You are helpful.") with open("recording.wav", "rb") as f: result = simple_transcribe(f.read(), api_key) print(result["text"]) ``` # Troubleshooting Source: https://docs.lokutor.com/sdks/troubleshooting Common problems with the Lokutor SDKs and how to fix them: failed connections, 402 and 429 at the handshake, WebSocket is not defined in Node.js, PyAudio and PortAudio installs, choppy or missing audio. ## Connection errors ### The WebSocket connection fails immediately A browser only sees close code `1006`, whatever the server said. The usual causes: * **The credential is wrong or expired.** Tickets (`wst_…`) last 10 minutes; with the JavaScript SDK use the `auth` option so a fresh one is fetched for every connection ([Secure browser setup](/guides/secure-browser-setup)). * **The balance is too low** (`402` at the handshake). Check the balance in the dashboard ([Billing errors](/api-reference/errors#billing-errors)). * **Too many sessions open** (`429` on `/ws/agent`). The account holds 3 at once before its first top-up, 10 after. Close sessions you are not using. * **The `agentId` is not on your account** (`404` `agent.not_found`). * A firewall or proxy blocks outbound connections on port 443. To see the real status, open the same URL from a server or with `curl -i` and read the response. ### `WebSocket is not defined` (Node.js) The SDK uses the global `WebSocket`, available in Node.js 22 and later. Upgrade Node.js. ## Audio issues ### The agent's voice is choppy or distorted * Usually network jitter. Check the connection. * If you send audio yourself, send 16 kHz, 16-bit mono PCM in steady \~20 ms chunks. * **Node.js:** the speaker must be set to 44.1 kHz, 16-bit, mono (`AUDIO_CONFIG`). ### No audio playback (Node.js) * Install `speaker` and pass a `NodeAudioManager` to `connect()` ([Node.js Setup](/guides/node-js-setup)). * Check that no other application holds the audio device exclusively, and that ALSA/PulseAudio is working on Linux. ### The microphone captures nothing * In a browser, the microphone must be requested from a click or tap. On iOS Safari, request it inside the tap with `requestMicrophone()` ([Starting a call on a phone](/sdk/agent#starting-a-call-on-a-phone)). * Check that permission was granted and the right input device is selected. ### The agent answers itself Its voice is leaking from the speakers into the microphone. Use headphones, or in a browser keep `echoCancellation` on (the default). ## Python ### `ModuleNotFoundError: No module named 'lokutor'` Install it with `pip install lokutor`, in the virtual environment you run from. ### PyAudio fails to install, or playback says PyAudio is missing PyAudio is only needed to play or record on the local machine, and it needs the PortAudio library: ```bash theme={null} brew install portaudio # macOS sudo apt install portaudio19-dev # Debian / Ubuntu pip install "lokutor[audio]" ``` Calling the API without local audio (`play=False`, transcribing files) works with plain `pip install lokutor`. *** For more help, write to [contact@lokutor.com](mailto:contact@lokutor.com). # Version History Source: https://docs.lokutor.com/version-history Release history and migration notes for @lokutor/sdk (JavaScript, latest 1.9.0) and lokutor (Python, latest 1.6.0) `@lokutor/sdk` latest: **1.9.0** · `lokutor` (Python) latest: **1.6.0** JS 1.5.0, 1.5.1 and 1.6.1 were JavaScript-only releases; Python went from 1.4.1 to 1.5.0 alongside JS 1.6.0. ## Changelog ### JS 1.9.0 (2026-10-26) * `language: 'auto'` (or `''`) on `VoiceAgentClient`, `ConversationalPanel` and `updateLanguage()` sends `{"type": "language", "data": ""}`, so the agent follows the caller's language ([Voice chat](/api-reference/voice-chat)). Before, the client and the panel turned an empty language into `'en'`. Omitting `language` is unchanged. New exports: `AUTO_LANGUAGE`, `LanguageOption`, `languageToWire()`. `client.language` can now be `''`. ### JS 1.8.0 · Python 1.6.0 (2026-10-21) * Custom vocabulary: `keyterms` on `STTClient.transcribe()` and `SpeechToTextClient`, the names, brands and terms to write your way when what is heard is close (up to 100; send `language` too). See [Custom vocabulary](/guides/custom-vocabulary). No other changes. ### JS 1.7.1 (2026-10-20) * `ConversationalPanel` draws its own orb (`PixelOrb`) when no visualizer is passed. 1.7.0 carried the same code and was never made public. ### JS 1.6.1 * JS: the microphone is low-passed before it is downsampled to 16 kHz for recognition. `StreamResampler` (which `BrowserAudioManager` uses) applies a 63-tap windowed-sinc filter at 0.45 × the output rate (7.2 kHz for 16 kHz) before interpolating. Without it, sound between 8 and 24 kHz folded back into the speech band. A 12 kHz tone used to come through at 4 kHz at full level and is now 85 dB down. Speech up to about 6 kHz keeps its level (−0.4 dB at 6 kHz, −4 dB at 7 kHz). * JS: from 44.1 kHz microphones, the resampled audio no longer depends on how it was split into blocks. The resampler lost part of a sample's timing at every block and ran slightly fast. * JS: `StreamResampler.process(chunk, true)` (flush) ends the stream when downsampling: it drains the filter, returns the remaining audio, and starts over. Upsampling is unchanged. No API changes. ### Game engines (preview), 2026-10-19 * New: [Unity and Godot SDKs](/guides/game-engines). A character with a Lokutor Agent listens through the microphone, answers in its own voice from its position in the world, moves its mouth, and calls game functions as actions. Unity: `com.lokutor.voice-agents` (git URL install). Godot: the `addons/lokutor` addon. Both in the `lokutor-sdk` repository; `@lokutor/sdk` and the Python SDK are unchanged. ### JS 1.6.0 / Python 1.5.0 * JS: `tool_call` fires once, with `{ name, arguments, call_id }`; pass `call_id` to `submitToolResult(call_id, result)`. It used to fire twice, the first time without `call_id`, so handlers ran each tool twice. * JS: constructor callbacks fire once, and connection errors and status changes reach both the constructor callbacks and `on('error')` / `on('status')` listeners. * JS: interim user text arrives as the new `transcription_partial` event and is no longer stored in `getTranscript()`, which holds final lines only. * JS: new `auth: () => string | Promise` option, called before every connect and reconnect, to fetch a fresh `wst_` ticket from your backend ([Secure browser setup](/guides/secure-browser-setup)). `apiKey` is optional when `auth` is given. * JS: with `agentId`, `prompt` is optional and `voice`, `language` and `prompt` are sent only if you set them, so the dashboard agent's own settings are no longer overwritten. * JS: `TTSClient.synthesize()` resolves when the server ends the stream and rejects with a `LokutorError` on server errors or stalls (it used to resolve after 2 s without audio). It sends `speed` and `steps` only if you set them. * JS: discovery helpers call `https://api.lokutor.com/voices` etc. (they requested a path that did not exist); `fetchHealth()` calls `GET /ready`. `SpeechToTextClient.connect()` rejects when the microphone fails. New error codes in `ErrorCode`: `billing.insufficient_balance`, `billing.topup_required`, `billing.limit_reached`, `billing.account_disputed`, `agent.not_found`. Node.js use needs Node 22+ (global `WebSocket`). * Python: `on_tool_call(name, arguments, call_id)` receives `call_id`. Works on Python 3.8+. PyAudio is only needed for local audio (`pip install "lokutor[audio]"`). Plain strings are accepted for `voice` and `language`. ### 1.5.1 * JS: new `requestMicrophone()`, to call inside the tap or click that starts a call; pass its result to `BrowserAudioManager` as `microphone`. The call then uses that stream instead of asking for the microphone after the connection opens, which iOS Safari could refuse without showing its prompt (the agent spoke and nothing the caller said reached it). It also moves an iOS audio session left in `'playback'` back to `'auto'`, since iOS refuses the microphone in playback mode. * JS: when the microphone cannot start, `connect()` now rejects with the new code `audio.microphone_unavailable` (not retryable) and closes the session. Previously `connect()` stayed pending while the session kept talking. * JS: `BrowserAudioManager.cleanup()` closes its AudioContext; `init()` no longer waits indefinitely on `AudioContext.resume()`. Server errors reach `onError` once (they were delivered twice). ### 1.5.0 * JS: the voice-agent client reconnects only after the connection drops or the server goes away (close codes 1001, 1006, 1011–1014). When the server ends the session on purpose (1000, 1008, 4xxx) it stays closed, fires `error` with code `session.ended` and the server's reason, status `disconnected`, and a new `ended` event — previously it reconnected into a fresh session. * JS: a reconnection reuses the running microphone (it used to start a second capture, doubling and scrambling the caller's audio) and resets the response generation counter (it used to discard every response of the new session as stale, so the agent answered and nothing was heard). * JS: new `session_limit` event when the server announces a session's remaining time; `ConversationalPanel` shows it as a countdown, says "Reconnecting…" while the client retries, ends the call visibly when the connection is gone, shows the server's reason, and adds `onEnded(message)`. * JS: `BrowserAudioManager` keeps the screen awake while the microphone is live (`keepAwake`, default `true`) and resumes audio when the page returns to the foreground. ### 1.4.1 * Python: `pyaudio` (needed only for local mic/speaker convenience — `VoiceAgentClient`'s live audio loop, and `TTSClient`/`STTClient`'s optional local playback/capture helpers) is now an optional `audio` extra (`pip install lokutor[audio]`) instead of a hard dependency. It needs PortAudio's C library, which doesn't compile on a clean machine without the system package — previously this broke `pip install lokutor` outright, and blocked even `TTSClient`/`STTClient` usage that never touches local audio hardware. ### 1.4.0 * JS: the voice-agent panel's "listening" curtain is now the agent's own accent color with a grain texture, replacing a fixed stock-photo background * JS: removed a leftover pulse animation and an opacity dim on the visualizer that were never updated for the current binary (agent/user, no idle) visualizer state * Backend: a false-positive barge-in that resumes playback now tells the client — previously the client was left showing `listening` while the bot was audibly still speaking (see [WebSocket Protocol → Barge-in](/guides/websocket-protocol#barge-in)) * Backend: `/ws/agent`'s `voice` and `language` messages now reject an unrecognised value the same way `POST /tts/synthesize` and `/ws/tts` already did, instead of silently applying a fallback ### 1.3.0 * Nine supported languages, Versa 2.0 voice ids * Wire vocabulary canonicalized to `voice`/`language` (the older `voice_id`/`lang` names remain accepted as deprecated aliases) ### 1.2.1 Point release on top of 1.2.0. ### 1.2.0 * Standalone speech-to-text: `STTClient` for one-shot transcription of a complete audio clip (`POST /stt/transcribe`), `SpeechToTextClient` for continuous/live transcription over `WS /ws/stt` — neither requires the full voice-agent (LLM + TTS) pipeline * `simpleTranscribe()` convenience function ### 1.1.43 * Tool calling improvements: `submitToolResult()` method, `call_id` in tool\_call events * Conversation panel UI component * Python SDK: `update_prompt()`, `get_transcript()`, `get_transcript_text()` * Python SDK: `on()` event listener pattern ### 1.1.17 * Initial stable release * `VoiceAgentClient` for real-time conversations * `TTSClient` for standalone text-to-speech * `BrowserAudioManager` for Web Audio API * `LokutorError` with typed error codes * WebSocket reconnection with exponential backoff * Viseme streaming support * 10 voices; language count at the time isn't preserved accurately in this entry — see [Voices, Languages & Models](/voices-languages-models) for the current count (nine) ## Versioning policy * **MAJOR** — Breaking API changes * **MINOR** — New features, backwards compatible * **PATCH** — Bug fixes, backwards compatible # Voices, Languages & Models Source: https://docs.lokutor.com/voices-languages-models The ten voice slots F1-F5 and M1-M5 and how they map to a native speaker per language, the thirteen spoken and nine recognised languages, the versa-2.0 model, and which request parameters change the audio ## Voices A voice is chosen by **slot**: five female (`F1`–`F5`) and five male (`M1`–`M5`). Each language has its own native speaker in each slot, so the speaker you hear depends on `language` as well as `voice`: `F1` in Spanish is a Spanish speaker and `F1` in English is an English speaker, not the same person speaking two languages. Keep `voice` and `language` together when you want a consistent result. `GET /voices` lists the slots with these display names: | ID | Name | Gender | | :- | :- | :- | | `F1` | Claire | Female | | `F2` | Sophie | Female | | `F3` | Emma | Female | | `F4` | Maria | Female | | `F5` | Isabella | Female | | `M1` | James | Male | | `M2` | Oliver | Male | | `M3` | Lucas | Male | | `M4` | Ethan | Male | | `M5` | Noah | Male | The names label the slot; they are the same whatever `language` you use. Where a language has no speaker of its own in a slot, the nearest slot of the same gender is used: Spanish `F2` sounds as `F1`, Italian `F3` as `F2`, Portuguese `M5` as `M4`, and French `M3`–`M5` as `M2`. English, Spanish, Catalan, Galician, Basque, Portuguese, French, Italian and German each have their own speakers; any other `language` value uses the English ones. Fetch the live list at runtime instead of hardcoding: ```bash theme={null} curl -s https://api.lokutor.com/voices ``` ```typescript theme={null} import { VoiceAgentClient } from '@lokutor/sdk'; const voices = await VoiceAgentClient.fetchVoices(); ``` Cloned voices (`clone_…` ids, created in the dashboard) are not slots: a clone is one speaker in every language, and only API keys on the account that created it can use it. ### Where the reference voices come from Each slot's speaker is a short reference recording of a real person who read text aloud for an open speech corpus. We credit the corpora here; the licence of each is the one its authors published. | Languages | Corpus | Licence | | :- | :- | :- | | English | VCTK (University of Edinburgh); Hi-Fi TTS (NVIDIA) | CC BY 4.0 | | Spanish (Spain) | Mozilla Common Voice 17, Spanish | CC0 | | German | Multilingual LibriSpeech (Meta); HUI-Audio-Corpus-German (LibriVox readers) | CC BY 4.0; CC0 | | French | SIWIS French Speech Synthesis Database (University of Edinburgh) | CC BY 4.0 | | Catalan | Festcat (Universitat Politècnica de Catalunya, Barcelona Supercomputing Center); Crowdsourced Catalan speech (OpenSLR 69, Google) | CC BY-SA 4.0 | | Galician | CRPIH UVigo GL Voices (Universidade de Vigo); Crowdsourced Galician speech (OpenSLR 77, Google) | CC BY 4.0; CC BY-SA 4.0 | | Basque | Crowdsourced Basque speech (OpenSLR 76, Google) | CC BY-SA 4.0 | | Italian | Mozilla Common Voice 17, Italian | CC0 | | Portuguese | Mozilla Common Voice, Portuguese (our subset is not split by country; two of the speakers are confirmed Brazilian) | CC0 | | Dutch, Polish | Mozilla Common Voice 17 | CC0 | | Romanian | VoxPopuli (Meta, European Parliament recordings); Mozilla Common Voice 17 | CC0 | | Russian | Russian LibriSpeech (OpenSLR 96, LibriVox audiobooks) | Public domain in the USA | Where a licence is share-alike (CC BY-SA 4.0), the speaker's recording is credited here and in the model's asset notes. The speakers are corpus readers, not product voice actors. The same slot names stay across versions; the person behind a slot in a language can change when we replace a reference with a clearer one, so pin the `language` and re-listen after a version change if your product depends on a specific timbre. ## Languages Versa speaks thirteen languages: nine it also understands (below) and four it only speaks. | Language | Code | | :- | :- | | English | `en` | | Spanish | `es` | | Catalan | `ca` | | Galician | `gl` | | Basque | `eu` | | Portuguese | `pt` | | French | `fr` | | Italian | `it` | | German | `de` | | Dutch | `nl` (speaks only) | | Polish | `pl` (speaks only) | | Romanian | `ro` (speaks only) | | Russian | `ru` (speaks only) | Every voice slot works in every one of these languages (see [Voices](#voices) for which speaker a slot resolves to). Dutch, Polish, Romanian and Russian have two speakers each, one female (`F1`) and one male (`M1`); every other female slot sounds as `F1` and every other male slot as `M1`. Fetch the live list at runtime rather than hardcoding it: ```typescript theme={null} const res = await fetch('https://api.lokutor.com/languages'); const { languages } = await res.json(); ``` ### Which languages are understood The thirteen above are the languages a voice can **speak**. Speech recognition, which voice agents and the speech-to-text API use to understand a caller, covers nine of them with one model: English, Spanish, Catalan, Galician, Basque, Portuguese, French, Italian and German. Recognition is told the agent's language on every call, which keeps one-word replies ("sí", "no") reliable; an agent set to detect the language lets the model work it out. ## Models | Model ID | Description | Default | | :- | :- | :- | | `versa-2.0` | Primary TTS model | Yes | `versa-1.0` has been retired and is no longer served. ## Parameters The current model, `versa-2.0`, is a distilled model that runs a fixed schedule of 4 denoising steps without guidance on every request. Several request parameters are therefore accepted for compatibility but do not change the audio: | Parameter | Where | Accepted values | Effect on `versa-2.0` | | :- | :- | :- | :- | | `speed` | REST, `/ws/tts`, SDKs | REST: outside 0.5–2.0 is reset to 1.0. `/ws/tts`: outside 0.5–2.0 is rejected (`validation.speed_out_of_range`) | Accepted for compatibility; no effect on versa-2.0. | | `steps` | REST, `/ws/tts`, SDKs | REST: 1–8, a higher value is treated as 8 (no error). `/ws/tts`: up to 128, above is rejected (`validation.steps_out_of_range`) | Accepted for compatibility; no effect on versa-2.0. | | `cfg`, `cfg_text` | REST, voice agent query parameters | REST: `cfg` 1–4, `cfg_text` 1–10 | Accepted for compatibility; no effect on versa-2.0. | | `quality` | REST (legacy) | `ultra_fast`, `fast`, `medium`, `high` | Ignored. | | `version` | `/ws/tts` | any string | Ignored; `versa-2.0` is the only model. | ### Speed The model takes its timing from its own duration model, and there is no rate control in the current graph. Accepted for compatibility; no effect on versa-2.0. ### Steps `steps` (called `nfe` server-side) is the number of denoising steps. The current model was trained for exactly 4 and always runs 4, on voice agents, WebSocket streams and REST alike. Accepted for compatibility; no effect on versa-2.0. On a live voice-agent session a per-session `nfe` can only be lowered, never raised above the default. ### Voice character `cfg` and `cfg_text` set guidance strength. The current model is trained to run without guidance: the voice comes from the reference speaker alone. Accepted for compatibility; no effect on versa-2.0.