Voice engine cookbook
For integrators who start voice calls from their own platform with sdkStartVoiceCall. The engine option is available on the test environment now and on production after the next release; to use LIVE on your workspace, ask us to enable it. The quickstart covers the full flow once; these recipes cover the parts you repeat: choosing an engine, joining, refusals, testing and monitoring.
Every example uses the test environment endpoint, https://api.wetel.dev/graphql. Keys minted there only work there. Call the mutation from your server: the API key must never reach a browser or app.
1. Start a call: default engine and LIVE
Section titled “1. Start a call: default engine and LIVE”Leave engine out and you get WORKFLOW, the default. Set engine: LIVE to ask for the live voice.
# Default enginecurl -sS https://api.wetel.dev/graphql \ -H 'content-type: application/json' \ -H "x-api-key: $WETEL_API_KEY" \ -H 'x-huat-platform: customer' \ --data '{ "query": "mutation($i: SdkStartVoiceCallInput!){ sdkStartVoiceCall(input:$i){ sessionId roomName expiresAt } }", "variables": { "i": { "agentId": 12, "clientId": "acct-1:call-9" } } }'
# Live engine: the same call with one more fieldcurl -sS https://api.wetel.dev/graphql \ -H 'content-type: application/json' \ -H "x-api-key: $WETEL_API_KEY" \ -H 'x-huat-platform: customer' \ --data '{ "query": "mutation($i: SdkStartVoiceCallInput!){ sdkStartVoiceCall(input:$i){ sessionId roomName expiresAt } }", "variables": { "i": { "agentId": 12, "clientId": "acct-1:call-9", "engine": "LIVE" } } }'These curl examples leave out livekitUrl and livekitToken on purpose, so the token does not land in your shell history. Your server needs them:
// Node 20+, an .mjs file. No packages.const GRAPHQL = "https://api.wetel.dev/graphql";
const MUTATION = ` mutation StartVoiceCall($i: SdkStartVoiceCallInput!) { sdkStartVoiceCall(input: $i) { sessionId livekitUrl livekitToken roomName expiresAt } }`;
export async function startVoiceCall(agentId, clientId, engine) { const input = { agentId, clientId }; if (engine) input.engine = engine; // "LIVE"; omit for the default
const res = await fetch(GRAPHQL, { method: "POST", headers: { "content-type": "application/json", "x-api-key": process.env.WETEL_API_KEY, // server side only "x-huat-platform": "customer", }, body: JSON.stringify({ query: MUTATION, variables: { i: input } }), }); const body = await res.json(); if (body.errors?.length) { const err = new Error(body.errors[0].message); err.graphql = body.errors[0]; // keep extensions for the recipes below throw err; } // { sessionId, livekitUrl, livekitToken, roomName, expiresAt } return body.data.sdkStartVoiceCall;}expiresAt is when the token stops being accepted for joining, about two minutes after the request. Treat livekitToken as one caller’s credential.
2. Join the room from a browser
Section titled “2. Join the room from a browser”The minimal flow: get livekitUrl and livekitToken from your server, connect, turn the microphone on, play the agent’s audio. The token is short-lived and belongs to one caller. If you hand it to a page by URL, put it in the fragment (/call#t=...): a fragment is not sent to any server, so it stays out of access logs. Read it, then remove it from the address bar. Never log it.
<div id="audio"></div><script src="https://cdn.jsdelivr.net/npm/livekit-client@2/dist/livekit-client.umd.min.js"></script><script> const { Room, RoomEvent, Track } = LivekitClient;
async function join() { const params = new URLSearchParams(location.hash.slice(1)); const livekitUrl = params.get("u"); const livekitToken = params.get("t"); history.replaceState(null, "", location.pathname); // drop the token from the address bar if (!livekitUrl || !livekitToken) throw new Error("Start a new call");
const room = new Room(); room.on(RoomEvent.TrackSubscribed, track => { if (track.kind === Track.Kind.Audio) { document.getElementById("audio").appendChild(track.attach()); } }); await room.connect(livekitUrl, livekitToken); // join immediately: the token is valid for about two minutes await room.localParticipant.setMicrophoneEnabled(true); // needs permission, HTTPS or localhost return room; } join().catch(console.error);</script>Pin the client script to an exact version in production rather than @2. The quickstart has the longer page with the agent state and the live transcript.
3. Handle VOICE_ENGINE_UNAVAILABLE (400)
Section titled “3. Handle VOICE_ENGINE_UNAVAILABLE (400)”LIVE is a deployment switch. Where it is off, the call is refused before anything is created or counted: BAD_REQUEST with extensions.originalError.code VOICE_ENGINE_UNAVAILABLE, and availableEngines lists the engines that work. Fall back to the default engine instead of failing the caller.
const original = e => e.graphql?.extensions?.originalError;
export async function startWithFallback(agentId, clientId, preferred = "LIVE") { try { return await startVoiceCall(agentId, clientId, preferred); } catch (e) { const o = original(e); if (o?.code !== "VOICE_ENGINE_UNAVAILABLE") throw e; const available = o.availableEngines ?? []; if (!available.includes("WORKFLOW")) throw e; console.warn("engine unavailable, using the default", { preferred, available, }); return startVoiceCall(agentId, clientId); // no engine: the default }}Remember what the fallback changes: the caller gets the workflow-driven call, with its tools and rules, instead of the live voice. Log it so you can see how often it happens.
4. Handle the busy refusal (429)
Section titled “4. Handle the busy refusal (429)”While the environment is already running its maximum number of live calls (one at a time on the test environment), a new call is refused with extensions.code TOO_MANY_REQUESTS, extensions.status 429 and extensions.retryAfterSeconds. Nothing is created or counted. Wait, with a little jitter, and try again a few times.
const sleep = ms => new Promise(r => setTimeout(r, ms));
export async function startWithBackoff( agentId, clientId, engine, maxTries = 5) { for (let attempt = 1; attempt <= maxTries; attempt++) { try { return await startVoiceCall(agentId, clientId, engine); } catch (e) { const x = e.graphql?.extensions; if (x?.code !== "TOO_MANY_REQUESTS" || attempt === maxTries) throw e; const wait = (x.retryAfterSeconds ?? 30) * 1000 + Math.random() * 2000; await sleep(wait); } }}If you start a call and never join it, it keeps its slot until the platform closes the unjoined session, about ten minutes after the request. Join right away, or do not start the call. A daily limit refusal is different (Daily voice call limit reached): do not retry it until the next UTC day. See limits and the busy-service recipe for a Python version.
5. Choosing an engine
Section titled “5. Choosing an engine”| You need | Choose |
|---|---|
| Answers that follow the agent’s published workflow, with its rules and guardrail nodes | WORKFLOW |
| Tools, knowledge search or approvals during the call | WORKFLOW |
| The transcript while the call is running | WORKFLOW (a LIVE transcript is stored after the call ends) |
| A faster, more natural-sounding live conversation from the agent’s instructions | LIVE |
| Behaviour identical to calls you already run | WORKFLOW, or leave engine out |
| Not sure | Try both on the same agent and listen; the trade-off is a judgment by ear |
LIVE answers from the agent’s instructions only: the workflow, its guardrail nodes and its tools do not run. Write the instructions so the agent can answer on its own, and keep anything that needs a rule or a tool on WORKFLOW. Neither engine is better in general; they trade control for conversational feel.
6. Test checklist
Section titled “6. Test checklist”- Call the agent once with the default engine and once with
engine: LIVE. Use a headset so the agent does not hear itself. - Listen. Check the greeting (it says it is an AI and offers a person), interrupt the agent mid-sentence, and ask something your workflow handles.
- Confirm the engine you asked for was used. A start that returned
sessionIdwithoutVOICE_ENGINE_UNAVAILABLEwas accepted with that engine. Then read the session with the sessions API: aLIVEcall has no workflow run for its turns and its transcript appears after the call ends, while aWORKFLOWcall shows workflow runs and the transcript as it goes. On request, our team can show thecall_startline for the call. - Test the refusals: ask for
LIVEsomewhere it is off and check your fallback; start a second call while one is running and check your backoff. - Close the page without joining once and check that your server does not hold on to the call.
7. Troubleshooting
Section titled “7. Troubleshooting”| Symptom | Likely cause |
|---|---|
BAD_REQUEST with VOICE_ENGINE_UNAVAILABLE | LIVE is not enabled on this environment. Read availableEngines, fall back to the default, or ask us to enable it. |
TOO_MANY_REQUESTS (429) with retryAfterSeconds | The environment is busy with another call. Wait that long and retry with backoff. |
UNAUTHENTICATED (Missing X-Api-Key header, Invalid API key) | Header missing, key wrong or revoked. |
FORBIDDEN | The x-huat-platform: customer header is missing, or voice calls are not enabled on the environment. |
| You join and hear nothing | Microphone permission was refused, or the page is not on HTTPS (localhost is allowed). Browsers only give a page the microphone on a secure origin. |
| Join refused | The token is older than about two minutes. Start a new call; never reuse a token. |
| Joined, but the agent never speaks | No voice worker is running for your session. Check with your Wetel contact. |
When you report a problem, send the sessionId, the time with seconds and timezone, and what you saw. Never send the livekitToken or your API key.
8. What to monitor in production
Section titled “8. What to monitor in production”- Call start success rate: the share of
sdkStartVoiceCallrequests that return a room, and the share refused, split byextensions.code(TOO_MANY_REQUESTS,BAD_REQUESTwithVOICE_ENGINE_UNAVAILABLE,FORBIDDEN,UNAUTHENTICATED). - Time to first audio, measured on your side: from the moment the caller joins to the first agent audio you play. Track it per engine so you can compare them with your own numbers.
- Join rate: calls started against calls joined. A gap means callers leaving before they join, or tokens expiring.
- Engine fallbacks: how often recipe 3 falls back to the default.
- Refusals by code, as an alert when
TOO_MANY_REQUESTSorFORBIDDENrises.
Never put the token or the API key in these logs or metrics.