Session API
Every export of the core package and every member of a session, grouped by what it does.
The core package exports four functions and the VoiceError class. Provider factories live on their own subpaths, such as voiceai-sdk/deepgram, and transports live on voiceai-sdk/twilio, voiceai-sdk/livekit and voiceai-sdk/ws.
import { createSession, getSession, listSessions, listVoices, VoiceError } from "voiceai-sdk";When the provider or the session fails, methods throw a VoiceError with a code. Expected outcomes, such as audio with no speech, come back as results instead. See Errors.
createSession
createSession(provider, options?) opens a connection to the provider and resolves with a Session. A session is an AsyncDisposable, so await using closes it when the scope ends, even if your code throws.
import { createSession } from "voiceai-sdk";
import { deepgram } from "voiceai-sdk/deepgram";
import { elevenlabs } from "voiceai-sdk/elevenlabs";
await using session = await createSession(
{ stt: deepgram(), tts: elevenlabs() },
{ language: "en-US", sampleRate: 16000, encoding: "pcm16", vad: { silenceMs: 600 } },
);provider takes one of three shapes:
- A speech-to-speech provider:
openai(). - A provider that does both directions:
google(),azure(),aws(),deepgram(),local()ormock(). - A pipeline that mixes providers:
{ stt: deepgram(), tts: elevenlabs() }.
Options
| Option | Type | What it does |
|---|---|---|
key | string | Your name for the session, such as "caller:+15551234567". If a live session has this key, you get that session back. |
language | string | The language to recognize and speak, such as "en-US". |
voice | string | The voice id to speak with. Get ids from listVoices. |
sampleRate | 8000, 16000, 24000 or 48000 | Sample rate of audio in and out, in Hz. |
encoding | "pcm16", "mulaw" or "opus" | Encoding of audio in and out. |
vad | { silenceMs?: number } or false | Voice activity detection. silenceMs is how long a pause ends a turn. false turns it off. |
timeoutMs | number | Close the session after this long in total, whatever is happening. |
idleTimeoutMs | number | Close the session after this long with no audio in or out. |
metadata | Record<string, string> | Your own labels, such as a tenant or call id. Not for secrets. |
If the provider can't honour an option, createSession throws a VoiceError with code unsupported. The SDK never ignores an option silently. See Capabilities.
getSession and listSessions
Pass a key and createSession returns the live session with that key if there is one, so a caller who reconnects resumes the same session. Without a match, it opens a new one.
getSession(provider, id) reconnects to a live session by its id. listSessions(provider) returns { id, key, startedAt, state }[] for the provider's live sessions.
import { getSession, listSessions } from "voiceai-sdk";
import { openai } from "voiceai-sdk/openai";
const provider = openai();
const sessions = await listSessions(provider);
for (const s of sessions) console.log(s.id, s.key, s.startedAt, s.state);
await using session = await getSession(provider, sessions[0].id);See Sessions and keys for how keys work across servers.
Identity
| Member | Value |
|---|---|
session.id | The session's id. Pass it to getSession to reconnect. |
session.key | The key you passed to createSession, if any. |
session.provider | The provider's name, such as "deepgram". |
session.capabilities | Booleans: streamingStt, streamingTts, speechToSpeech, wordTimings, diarization, interruptions and voices. |
Capabilities explains each flag and how a pipeline combines them. The examples below assume a session opened as above.
Speech-to-text
session.transcribe(audio, opts?)
Batch recognition. audio is a Uint8Array, ArrayBuffer, Blob or ReadableStream. It resolves with { ok, text, words, language, durationMs, reason? }. Each entry in words is { text, startMs, endMs, confidence }.
const result = await session.transcribe(await Bun.file("call.wav").bytes());
if (result.ok) {
for (const w of result.words) console.log(w.startMs, w.endMs, w.text, w.confidence);
} else {
console.log("no transcript:", result.reason);
}When there is no transcript, ok is false and reason is "no_speech", "timeout" or "unsupported_audio". These are results, not exceptions.
session.listen(stream)
Streaming recognition. stream is an AsyncIterable<Uint8Array> or a ReadableStream. It returns an async iterable of { type, text, startMs, endMs, speaker? }, where type is "partial" or "final".
for await (const t of session.listen(Bun.file("call.pcm").stream())) {
if (t.type === "final") console.log(t.speaker ?? "?", t.text);
}A partial can change as more audio arrives. A final is settled. speaker is set only when the session supports diarization.
Text-to-speech
session.speak(text, opts?)
text is a string, or an AsyncIterable<string> such as streaming LLM output. opts takes voice, speed and format. Which values they accept depends on the provider.
It returns a Speech. Await it for { ok, audio, durationMs, characters }, or iterate it to get { data, ms } chunks as they are made.
import { createSession, listVoices } from "voiceai-sdk";
import { elevenlabs } from "voiceai-sdk/elevenlabs";
const voices = await listVoices(elevenlabs());
await using session = await createSession(elevenlabs(), { voice: voices[0].id });
// Await it for the whole clip.
const result = await session.speak("Your order has shipped.");
console.log(result.ok, result.durationMs, result.characters);
// Or iterate it to use chunks as they arrive.
for await (const chunk of session.speak("It should arrive on Friday.")) {
process.stdout.write(chunk.data);
}Pass an async iterable to start speaking before the whole reply exists:
async function* reply() {
yield "Let me check that. ";
yield "Your order shipped this morning.";
}
await session.speak(reply());listVoices(provider)
Lists the voices a provider offers as { id, name, language, gender? }[]. Pass an id as the voice option, or as voice in speak options for a single call.
Conversation
session.connect(transport)
Attaches audio in and out. Once connected, the session hears the transport's audio and speaks into it.
| Transport | Import from |
|---|---|
twilioMediaStream(ws) | voiceai-sdk/twilio |
livekitRoom(room, { identity }) | voiceai-sdk/livekit |
webSocketAudio(ws) | voiceai-sdk/ws |
session.converse(handler)
Runs the turn loop. For each final transcript it calls handler(text, ctx) and speaks the string or AsyncIterable<string> the handler returns. It handles barge-in, and resolves when the session closes.
ctx is { signal, history, session }. signal aborts when the reply is no longer wanted, such as when the caller talks over it, so pass it to your model call. history holds the conversation so far.
import { createSession } from "voiceai-sdk";
import { deepgram } from "voiceai-sdk/deepgram";
import { elevenlabs } from "voiceai-sdk/elevenlabs";
import { twilioMediaStream } from "voiceai-sdk/twilio";
import { answer } from "./answer.js"; // your model call
export async function handleCall(ws: WebSocket) {
await using session = await createSession({ stt: deepgram(), tts: elevenlabs() });
session.connect(twilioMediaStream(ws));
await session.say`Thanks for calling. How can I help?`;
await session.converse((text, { signal, history }) => answer(text, history, signal));
}session.say
A tagged template that speaks into the connected transport. With no transport connected, it resolves with a SpeakResult instead. Interpolated values are spoken as plain text, never as SSML, so user input can't inject markup.
const name = "Ana <break time='3s'/>";
await session.say`Thanks, ${name}. One moment.`; // the tag is not treated as SSMLsession.interrupt()
Stops the current speech now. converse does this for you on barge-in. Call it yourself to cut a reply short.
session.pause() and session.resume()
Pause and resume the session. Support depends on the provider. Where it isn't available, both throw VoiceError with code unsupported, and there is no capability flag for it.
try {
await session.pause();
} catch (err) {
if (!(err instanceof VoiceError && err.code === "unsupported")) throw err;
}Events
session.on(event, fn) registers a listener for one of six events.
| Event | Fires when |
|---|---|
transcript | A partial or final transcript arrives. |
interrupt | Speech stops early, because the caller talked over it or you called session.interrupt(). |
speech.start | The session starts playing speech. |
speech.end | The speech finishes or is cut off. |
error | A failure happens that isn't tied to a call you are awaiting. The listener gets a VoiceError. |
close | The session closes, whether you, the transport or the provider closed it. |
session.on("transcript", (t) => console.log(t.type, t.text));
session.on("error", (err) => console.error(err.code, err.provider));
session.on("close", () => console.log("session closed"));Lifecycle
session.close()
Closes the session and releases the provider connection. It is idempotent, so calling it twice is safe. await using calls it for you at the end of the scope. Calls on a closed session throw VoiceError with code closed.
Set idleTimeoutMs to close sessions that stop receiving audio. See Lifecycle and cleanup.
session.usage()
Returns what the session has used so far: { audioInMs, audioOutMs, characters }. audioInMs is audio heard, audioOutMs is audio spoken, and characters counts text sent to speech.
const { audioInMs, audioOutMs, characters } = session.usage();
console.log({ session: session.id, audioInMs, audioOutMs, characters });Escape hatches
session.native is the provider's own client or socket. session.ext.<provider> holds helpers specific to that provider. Use them only for what the session API doesn't cover: code that uses them works with that provider alone. See Native API.