Appearance
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.
connectRealtimeworks with the browserWebSocket, Node 22+'s global one, or thewspackage.- Browser helpers:
startMicrophone()(getUserMedia + AudioWorklet → PCM16 24 kHz chunks) andcreateAudioPlayer()(gapless playback, interrupted when the user starts talking).
bash
npm install @hevkar/realtimeFlow
- 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. - 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.
| Option | Description |
|---|---|
token, url | from POST /v1/realtime/sessions |
WebSocket | implementation (default globalThis.WebSocket) |
tokenIn | 'query' (default, ?token=) or 'protocol' (Sec-WebSocket-Protocol, keeps the token out of URLs and logs) |
binaryAudio | send audio as raw binary frames instead of base64 JSON (default false) |
timeoutMs | connect timeout (default 15 s) |
RealtimeConnection
| Member | Description |
|---|---|
session | the session.ready event (sessionId, agent, expiresAt, maxSeconds, audioFormat) |
on(type, fn) / once / off | typed 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() }>.
| Option | Description |
|---|---|
onChunk | receives each Int16Array chunk, for example conn.sendAudio |
chunkMs | chunk length (default 100 ms) |
audioContext | an existing AudioContext to use |
mediaStream | an existing MediaStream to use instead of getUserMedia |
constraints | getUserMedia 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.
| Option | Description |
|---|---|
audioContext | defaults to a new AudioContext (browser) |
leadSeconds | small lead time before the first chunk, smoothing network jitter |
| Member | Description |
|---|---|
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 |
bufferedSeconds | seconds of queued audio not yet played |
playing | whether audio is playing |
close() | release the player |
Helpers
pcm16ToBase64, base64ToPcm16, floatToPcm16, pcm16ToFloat, Resampler, ChunkBuffer, encodeClientEvent, decodeServerEvent.