Skip to content

Realtime voice ​

Realtime agents hold live voice conversations: the end user speaks, the agent answers with synthesized speech, with low latency and barge-in. Hevkar relays the session to the model provider (OpenAI Realtime or Gemini Live) and speaks one normalized protocol to your app, whatever provider the agent uses.

How it works ​

 end user's app                your backend                  Hevkar
 ──────────────                ────────────                  ──────
 "start call"  ──────────────►  POST /v1/realtime/sessions ──►  checks, creates session
               ◄──────────────  { token, url }            ◄──
 WS url?token=… ───────────────────────────────────────────────►  opens provider session
               ◄─────────────────────────────────── session.ready
 audio ⇄ audio, transcripts, tool events ◄────────────────────►
  1. Your backend creates a session with its API key (scope realtime:session) and receives a short-lived, single-use token.
  2. The app connects to the WebSocket with the token and streams microphone audio.
  3. The platform runs the agent's instructions, voice, turn detection and tools server-side and meters usage live.

Your API key never leaves your server.

Configure the agent ​

Create an agent of type realtime. Its realtime settings:

FieldDefaultMeaning
provideropenai or gemini
modelIdan enabled realtime model
voiceprovider voice name
turnDetectionserver_vadserver_vad: the server detects the end of the user's turn; none: push-to-talk, the app commits turns
maxSessionMinutes151 to 120
storeTranscripttruekeep the transcript with the session

instructions and tools (built-in, HTTP, live data source and agent tools) apply as for other agents; at most maxToolCalls tool calls per user turn, 30 s each. Publish the agent before creating API sessions.

1. Create a session (backend) ​

bash
curl "$HEVKAR_BASE_URL/v1/realtime/sessions" \
  -H "Authorization: Bearer $HEVKAR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"agent": "voice-concierge", "externalUserId": "user_42", "metadata": {"plan": "pro"}}'
ts
// e.g. in your GET /voice-token route, after authenticating your user
const { token, url, expiresAt, sessionId } = await hevkar.realtime.createSession({
  agent: 'voice-concierge',
  externalUserId: user.id,
});
res.json({ token, url });
ts
const session = await fetch(`${baseUrl}/v1/realtime/sessions`, {
  method: 'POST',
  headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({ agent: 'voice-concierge', externalUserId: user.id }),
}).then((r) => r.json());

Response 201:

json
{
  "token": "eyJhbGciOiJIUzI1NiIs…",
  "url": "wss://api.example.com/v1/realtime",
  "expiresAt": "2026-11-21T10:17:00.000Z",
  "sessionId": "a6d1…"
}

The token must be used within about two minutes (expiresAt) and only once. It is bound to the session, agent version, end user, API key and maximum duration.

Checks at this point, in this order:

ErrorWhen
403 MISSING_SCOPEthe key lacks realtime:session
404 NOT_FOUNDno agent with this slug
403 AGENT_NOT_ALLOWEDthe key is restricted to other agents
400 AGENT_NOT_REALTIMEthe agent is not a realtime agent (checked before publication)
409 AGENT_NOT_PUBLISHEDthe agent has no published version
403 ORG_SUSPENDEDthe organization is suspended
402 QUOTA_EXCEEDEDthe monthly spend cap is reached
400 REALTIME_NOT_CONFIGUREDthe agent has no realtime settings
400 MODEL_UNAVAILABLEthe realtime model is unknown, disabled or not a realtime model
429 REALTIME_SESSION_LIMITthe organization has reached its concurrent session limit (pending sessions count until their token expires)

2. Connect (browser) ​

Use @hevkar/realtime: it handles the protocol, microphone capture (PCM16 at 24 kHz) and gapless playback with barge-in.

ts
import { connectRealtime, createAudioPlayer, startMicrophone } from '@hevkar/realtime';

startButton.onclick = async () => {
  const { token, url } = await fetch('/voice-token').then((r) => r.json());
  const conn = await connectRealtime({ token, url, tokenIn: 'protocol' });

  const player = createAudioPlayer(); // create it in a click handler (autoplay policy)
  player.attach(conn); // plays audio.delta, stops on speech.started

  conn.on('transcript.done', (e) => console.log(`${e.role}: ${e.text}`));
  conn.on('session.ended', (e) => console.log('ended:', e.reason));

  const mic = await startMicrophone({ onChunk: (pcm) => conn.sendAudio(pcm) });
  conn.createResponse(); // optional: let the agent greet first

  stopButton.onclick = async () => {
    await mic.stop();
    player.close();
    conn.close();
  };
};

With turnDetection: "none" call conn.commit() when the user releases the talk button.

Protocol ​

Every frame is JSON text with a type. You only need this section if you implement the protocol yourself (another language, a native app).

Connecting ​

Open the url from the session response with the token either

  • as a query parameter: wss://…/v1/realtime?token=<token>, or
  • as subprotocols: Sec-WebSocket-Protocol: hevkar-realtime, token.<token> (the server selects hevkar-realtime). Use this in browsers to keep the token out of URLs and logs.

The server verifies the token, opens the provider session and sends session.ready. Frames you send before that are buffered.

Audio format ​

PCM16, little-endian, mono, 24 kHz, in both directions, base64-encoded in JSON frames. Clients may also send audio as binary frames of raw PCM16 (same format, no base64). A client frame may be at most 1 MiB; one input_audio.append carries at most about 512 KiB of audio. (For Gemini the platform resamples to 16 kHz internally.)

Client to server ​

typeFieldsMeaning
input_audio.appendaudio (base64)microphone audio
input_audio.commitend of the user's turn: commit the audio and request a response (push-to-talk; with server VAD the server does this)
input_audio.cleardrop uncommitted audio (OpenAI; no-op on Gemini)
conversation.item.createtext (1 to 20 000 chars)a typed user message; the model answers it
response.createmake the model speak now (for example a greeting)
response.cancelcancel the running response (OpenAI; on Gemini responses stop on barge-in only)
session.updatesession: {instructions?, voice?, turnDetection?}OpenAI only (UNSUPPORTED on Gemini); instructions are appended to the agent's

An invalid frame gets error {code: "INVALID_EVENT"} and the session continues.

Server to client ​

typeFields
session.readysessionId, agent {id, slug, name, version} (version null for console drafts), expiresAt, maxSeconds, audioFormat {encoding: "pcm16", sampleRate: 24000, channels: 1}
audio.deltaaudio (base64 PCM16 24 kHz)
audio.donethe assistant's audio for this response is complete
transcript.delta / transcript.donerole (user or assistant), text
speech.started / speech.stoppedthe user started / stopped talking; on speech.started stop playback (barge-in)
tool.callname (tools run server-side)
tool.resultname, ok
response.doneusage of this response: inputTokens, cachedInputTokens, outputTokens, audioInputSeconds, audioOutputSeconds, priceMicros
errorcode, message
session.endedreason, usage (session totals)

End reasons ​

reasonMeaning
client_closedthe app closed the socket
upstream_closedthe provider closed its session
max_durationthe session reached its maximum duration
limitthe organization's monthly spend cap was reached mid-session
idleno client frames for a while (5 minutes by default)
slow_clientthe client did not read fast enough; no session.ended is sent
errorprovider or server error
server_shutdownthe server is restarting

Close codes ​

CodeWhen
1000normal end
4401token rejected: TOKEN_INVALID, TOKEN_EXPIRED or TOKEN_USED (sent as an error first)
4402max_duration or limit
4408slow_client: the app did not read events fast enough (no session.ended is sent)
4500provider or server error

An invalid client message does not close the session: the server answers it with an error event (INVALID_EVENT, or UNSUPPORTED for a feature the provider lacks) and goes on.

A used or expired token cannot be reused: create a new session.

Limits and metering ​

  • Maximum duration: the agent's maxSessionMinutes, capped by the platform maximum (2 hours by default), counted from connect. session.ready.maxSeconds and expiresAt tell you the limit.
  • The spend cap is checked after every response and periodically during the session.
  • Both sides are pinged regularly; a peer that does not answer is dropped.
  • Usage is metered per response and at the end: audio seconds in and out (from the audio actually relayed) and text tokens. response.done.usage.priceMicros lets you show running costs.
  • Child runs of agent tools are linked to the realtime session.

Sessions and transcripts are visible in the console under the agent's sessions.

Hevkar public API v1