Skip to content

Realtime client ​

@hevkar/realtime connects browsers and Node.js to realtime voice sessions (WS /v1/realtime). It speaks the platform's normalized protocol, so the same code works whether the agent runs on OpenAI Realtime or Gemini Live.

  • ESM and CommonJS builds with type declarations; no runtime dependencies.
  • connectRealtime works with the browser WebSocket, Node 22+'s global one, or the ws package.
  • Browser helpers: startMicrophone() (getUserMedia + AudioWorklet → PCM16 24 kHz chunks) and createAudioPlayer() (gapless playback, interrupted when the user starts talking).
bash
npm install @hevkar/realtime

Flow ​

  1. Your backend mints a token with its API key (never ship the key to the app): POST /v1/realtime/sessions {agent, externalUserId} → {token, url, expiresAt, sessionId} (with the SDK: hevkar.realtime.createSession(...)). The token is single-use and must be used within about two minutes.
  2. The app connects with the token and streams audio.

Browser example ​

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

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

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

conn.on('transcript.done', (e) => console.log(`${e.role}: ${e.text}`));
conn.on('tool.call', (e) => console.log('running tool', e.name));
conn.on('response.done', (e) => console.log('cost (USD micros)', e.usage.priceMicros));
conn.on('session.ended', (e) => console.log('ended:', e.reason));

const mic = await startMicrophone({ onChunk: (pcm) => conn.sendAudio(pcm) });

// With turn detection "server_vad" (default) the server detects when the user stops talking.
// With "none", end the turn yourself (push-to-talk):
//   conn.commit();

// Later:
await mic.stop();
player.close();
conn.close();

Node example ​

ts
import WebSocket from 'ws';
import { connectRealtime } from '@hevkar/realtime';

const conn = await connectRealtime({ token, url, WebSocket });
conn.sendText('Hello!');
conn.on('audio.delta', (e) => speaker.write(Buffer.from(e.audio, 'base64')));

connectRealtime(options) ​

Returns Promise<RealtimeConnection>, resolved on session.ready. Rejects with RealtimeConnectError (with a code such as TOKEN_EXPIRED, TOKEN_USED, TOKEN_INVALID, PROVIDER_ERROR, TIMEOUT) when the session cannot start.

OptionDescription
token, urlfrom POST /v1/realtime/sessions
WebSocketimplementation (default globalThis.WebSocket)
tokenIn'query' (default, ?token=) or 'protocol' (Sec-WebSocket-Protocol, keeps the token out of URLs and logs)
binaryAudiosend audio as raw binary frames instead of base64 JSON (default false)
timeoutMsconnect timeout (default 15 s)

RealtimeConnection ​

MemberDescription
sessionthe session.ready event (sessionId, agent, expiresAt, maxSeconds, audioFormat)
on(type, fn) / once / offtyped events: every server event type, '*' and 'close' ({code, reason}); on returns an unsubscribe function
sendAudio(pcm)PCM16 mono 24 kHz (Int16Array, ArrayBuffer or Uint8Array)
commit()end the user's turn and request a response
clearAudio()drop uncommitted audio
sendText(text)typed user message (answered)
createResponse()make the model speak now (for example a greeting)
cancel()cancel the current response
updateSession({instructions?, voice?, turnDetection?})OpenAI agents only
close()end the session

Server events and their fields: Protocol. Close codes: Close codes.

startMicrophone(options) ​

Browser only. Captures the microphone and emits PCM16 mono 24 kHz chunks, resampling from the device rate. Returns Promise<{ muted, stop() }>.

OptionDescription
onChunkreceives each Int16Array chunk, for example conn.sendAudio
chunkMschunk length (default 100 ms)
audioContextan existing AudioContext to use
mediaStreaman existing MediaStream to use instead of getUserMedia
constraintsgetUserMedia audio constraints (echo cancellation etc. on by default)

Set mic.muted = true to stop sending without releasing the device; await mic.stop() releases it and flushes the last partial chunk.

createAudioPlayer(options?) ​

Gapless PCM16 24 kHz playback through Web Audio.

OptionDescription
audioContextdefaults to a new AudioContext (browser)
leadSecondssmall lead time before the first chunk, smoothing network jitter
MemberDescription
enqueue(audio)queue an audio.delta (base64) or PCM16 samples
interrupt()stop at once and drop the queue (barge-in)
attach(conn)play the connection's audio.deltas and interrupt on speech.started; returns an unsubscribe function
bufferedSecondsseconds of queued audio not yet played
playingwhether audio is playing
close()release the player

Helpers ​

pcm16ToBase64, base64ToPcm16, floatToPcm16, pcm16ToFloat, Resampler, ChunkBuffer, encodeClientEvent, decodeServerEvent.

Hevkar public API v1