API Reference
WS/v1/realtime

Voice Agents

A voice agent composes speech-to-text, an LLM, and text-to-speech into one live, two-way phone-call-style conversation over a single WebSocket — speak audio in, get audio back out. Create one with its own instructions and voice, mint a one-time connection token right before each call, then drop the returned ws_url into any platform that can open a WebSocket: a video-call app, a telephony bridge, an IVR, or your own frontend.

1. Create an agent

stt_model / llm_model / tts_model are optional and default to the platform's recommended combination. instructions is the agent's system prompt / scope — see Template variables below for the {{customer_name}} syntax used here.

bash
curl https://api.inferexai.in/v1/voice-agents \
  -H "Authorization: Bearer sk-live-your-key" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Support line agent",
    "instructions": "You are a helpful support agent. The caller'\''s name is {{customer_name}}. Greet them by name."
  }'
response.json
{
  "agent_id": "va_8e7fc08b13ef759fc807",
  "name": "Support line agent",
  "realtime": {
    "token_endpoint": "/v1/realtime/token",
    "method": "POST",
    "body": { "agent_id": "va_8e7fc08b13ef759fc807" },
    "note": "POST here with your API key to get a one-time ws_url — do not embed your API key directly in a wss:// URL."
  }
}

The create/get response no longer hands back a connectable ws_url directly — embedding a raw API key in a wss:// URL leaks it into access logs, browser history, and anywhere that URL gets pasted. Call POST /v1/realtime/token instead, right before each call.

2. Get a connection token

Over HTTPS, with your real API key, immediately before connecting. The returned ws_url is single-use and expires in expires_in seconds (120 today) — mint a fresh one for every call rather than caching it.

bash
curl https://api.inferexai.in/v1/realtime/token \
  -X POST \
  -H "Authorization: Bearer sk-live-your-key" \
  -H "Content-Type: application/json" \
  -d '{ "agent_id": "va_8e7fc08b13ef759fc807" }'
response.json
{
  "token": "rtt_9f2b1c...",
  "expires_in": 120,
  "ws_url": "wss://api.inferexai.in/v1/realtime?agent=va_8e7fc08b13ef759fc807&token=rtt_9f2b1c..."
}

Append &caller_ref= and any &var_*= params (see Template variables below) onto this ws_url yourself before opening the socket — the token only carries the agent id.

3. Audio format

You sendPCM16, mono, 16kHz, base64-encoded
You receivePCM16, mono, 24kHz, base64-encoded

If your platform's media pipeline uses something else (Opus from a video SDK, μ-law/8kHz from telephony), resample/transcode at the boundary — the gateway doesn't negotiate format, it always speaks PCM16 at the rates above.

4. Message protocol

JSON events over the WebSocket, using the widely used realtime event names below. A client that already sends and receives these events works with little or no change.

You send
input_audio_buffer.append{ "audio": "<base64 pcm16>" } — stream caller audio in, small chunks (e.g. 20ms frames).
input_audio_buffer.commitOptional — force end-of-turn manually instead of relying on voice-activity detection.
input_audio_buffer.closeEnd the call from your side (closing the socket works too).
You receive
session.createdHandshake done, session is live.
input_audio_buffer.speech_started / .speech_stoppedServer-side VAD turn boundaries on the caller’s audio.
conversation.item.input_audio_transcription.delta / .completedLive STT transcript of what the caller said.
response.createdThe agent is starting to reply.
response.output_audio.delta{ "delta": "<base64 pcm16>" } — agent speech, stream straight to playback.
response.output_audio_transcript.delta / .doneLive transcript of the agent’s reply — use for on-screen captions.
response.doneThe agent’s turn is fully finished (includes usage/latency metadata).
error{ "error": { "message", "code" } }
Barge-in: sending new caller audio while response.output_audio.delta is still streaming cancels the in-flight agent turn and starts a fresh one — no explicit "stop" event needed.
Call end: the agent can end the call itself (e.g. the caller says goodbye). The socket closes with code 1000, reason caller_ended_call, after the final response.done — treat that close reason as the agent hanging up, not an error.

5. Code

Node.js

voice-agent.ts
// 1. Mint a one-time connection token over HTTPS, right before connecting
const tokenRes = await fetch("https://api.inferexai.in/v1/realtime/token", {
  method: "POST",
  headers: {
    Authorization: "Bearer sk-live-your-key",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ agent_id: "va_xxx" }),
});
const { ws_url } = await tokenRes.json();

// 2. Connect with it — append caller_ref / var_* here, not the raw API key
const ws = new WebSocket(`${ws_url}&caller_ref=caller-42`);

ws.on("open", () => {
  // stream caller audio in as it's captured — PCM16, mono, 16kHz
  callerAudioStream.on("data", (pcm16Chunk) => {
    ws.send(JSON.stringify({
      type: "input_audio_buffer.append",
      audio: pcm16Chunk.toString("base64"),
    }));
  });
});

ws.on("message", (raw) => {
  const evt = JSON.parse(raw);
  switch (evt.type) {
    case "response.output_audio.delta":
      playbackSink.write(Buffer.from(evt.delta, "base64")); // PCM16, mono, 24kHz
      break;
    case "response.output_audio_transcript.done":
      renderCaption(evt.transcript);
      break;
    case "error":
      console.error("voice agent error", evt.error);
      break;
  }
});

ws.on("close", (code, reason) => {
  if (reason.toString() === "caller_ended_call") {
    // the agent hung up on its own — tear down the call leg cleanly
  }
});

Python

voice_agent.py
import asyncio, base64, json, httpx, websockets

async def run_call(agent_id, api_key, caller_ref, caller_audio_chunks, on_audio, on_caption):
    # 1. Mint a one-time connection token over HTTPS, right before connecting
    async with httpx.AsyncClient() as http:
        r = await http.post(
            "https://api.inferexai.in/v1/realtime/token",
            headers={"Authorization": f"Bearer {api_key}"},
            json={"agent_id": agent_id},
        )
        ws_url = r.json()["ws_url"]

    # 2. Connect with it — append caller_ref / var_* here, not the raw API key
    url = f"{ws_url}&caller_ref={caller_ref}"
    async with websockets.connect(url) as ws:
        async def sender():
            async for pcm16_chunk in caller_audio_chunks:  # PCM16, mono, 16kHz
                await ws.send(json.dumps({
                    "type": "input_audio_buffer.append",
                    "audio": base64.b64encode(pcm16_chunk).decode(),
                }))

        async def receiver():
            async for raw in ws:
                evt = json.loads(raw)
                if evt["type"] == "response.output_audio.delta":
                    on_audio(base64.b64decode(evt["delta"]))  # PCM16, mono, 24kHz
                elif evt["type"] == "response.output_audio_transcript.done":
                    on_caption(evt["transcript"])
                elif evt["type"] == "error":
                    print("voice agent error:", evt["error"])

        await asyncio.gather(sender(), receiver())

Wire your own audio capture/playback and participant id into these two handlers — the protocol is the same regardless of what's embedding it (a telephony SDK, a video-call platform, a browser tab).

6. Caller memory

Pass ?caller_ref=<your id> — a phone number, user id, or participant id — and the agent's conversation history carries over the next time the same caller_ref connects to this agent. Omit it and each call starts with no prior context.

7. Template variables

Write placeholders directly in instructions — {{customer_name}}, or anything else — then fill them in per call with ?var_<name>=<value> query params on the connect URL. One static agent and ws_url, different content every call.

Name personalization
Instructions: "The caller's name is {{customer_name}}. Greet them by name."
connect URL
wss://api.inferexai.in/v1/realtime?agent=va_xxx&token=<one-time token>&var_customer_name=Priya
JD-scoped interview agent
One agent, a different job description per interview. Instructions: "Only ask questions relevant to this job description: {{job_description}}"
connect URL
wss://api.inferexai.in/v1/realtime?agent=va_xxx&token=<one-time token>&var_job_description=<url-encoded JD text>

Limits: 4,000 characters per variable, 8,000 combined, 10 variables max. Exceeding any of these is rejected with HTTP 400 before the WebSocket upgrades — a failed connect, not a mid-call error. For job descriptions or other content that's long-lived rather than per-call, consider one agent per role (baked directly into instructions) instead of passing it as a variable on every connect.

A variable you forget to pass stays as the literal {{job_description}} text rather than vanishing — a missing param is obvious the moment you test, not a silent miswire.

8. Channels

Besides this WebSocket, the same agent can take calls on phone numbers (your SIP trunk, in and out), WhatsApp and a website call button, any or all at once (portal: agent → Build → Channels). Each call records its channel: realtime_audio (this WebSocket), phone, whatsapp, web or text, and GET /v1/voice-agents/calls?channel= filters by it.

9. Duplicate an agent

POST /v1/voice-agents/{id}/duplicate with an optional {"name": "…"} makes a new agent from the live version's settings: instructions, greeting, voice and models, tools, knowledge, outcomes, captured fields and call behaviour. It is named "… (copy)" unless you give a name. Phone numbers, WhatsApp numbers, widgets, call history and caller memory stay with the original. In the portal: the agent's actions → Duplicate.

Cost

Billed per turn across the three underlying legs — speech-to-text (by audio duration), the LLM (by token usage), and text-to-speech (by characters synthesized) — each tagged with the same request id, so a single turn is visible as one line in Observability even though three models ran. Live rates are the same per-model rates shown on GET /v1/models.

Error codes

Setup failures (bad agent id, no credit, no scope, oversized template variables) are returned as a normal HTTP response code — either from POST /v1/realtime/token or, if the token itself is invalid/expired/reused, on the WebSocket handshake before it upgrades — so they're visible to any client, not just one that inspects close frames.

400
agent_required / too_many_vars / var_too_large / vars_too_large
Missing ?agent=, or template variables exceed the limits above.
401
unauthorized
Missing or invalid API key.
402
payment_required
Wallet is empty. Top up before retrying.
403
kyc_required / forbidden
KYC verification is required, or the key lacks the "audio" scope.
404
agent_not_found / no_route / no_realtime_route
The agent id doesn’t exist (or isn’t yours), or one of its underlying models has no active route.
503
stream_unavailable
Setup failed unexpectedly. Retry after a short wait.