Create a real-time phone voice agent from scratch with Twilio Media Streams, Together AI realtime STT, chat completions, realtime TTS, and local voice activity detection.
This guide walks through creating a phone-based voice agent. You will create a local TypeScript server that answers an inbound Twilio call, streams audio over WebSockets, detects turn boundaries locally with Silero VAD, sends the caller’s speech to Together AI for transcription, generates a reply with a chat model, synthesizes that reply back to speech, and plays it into the same call.
Architecture
Requirements
Before you start, make sure you have:
Node.js 18+.
A Together AI account and API key.
A Twilio account with a voice-capable phone number.
ngrok or another HTTPS tunnel for local testing.
The Silero VAD ONNX model saved in your project root as silero_vad.onnx.
Step 1: Create the project
Create a new directory and install the dependencies:
account_exec - an account executive at Together AI.
marcus - an engineer at Together AI.
Step 3: Add the audio conversion layer
Create audio-convert.ts. This file handles:
mu-law encode and decode - this is needed to convert audio I/O over the phone.
sample-rate conversion between 8 kHz(needed for phone), 16 kHz(needed for STT), and 24 kHz(output by TTS).
parsing WAV headers when the first TTS chunk arrives with a WAV header attached.
converting Twilio chunks into Together STT input.
converting Together TTS output back into Twilio playback audio.
audio-convert.ts
audio-convert.ts
// G.711 mu-law codec, resampling, and WAV utilities// Mu-law decode table (256 entries: mulaw byte -> int16 sample)const MULAW_DECODE_TABLE: Int16Array = (() => { const table = new Int16Array(256); for (let i = 0; i < 256; i++) { const byte = ~i & 0xff; const sign = byte & 0x80; const exponent = (byte >> 4) & 0x07; const mantissa = byte & 0x0f; let magnitude = ((mantissa << 3) + 0x84) << exponent; magnitude -= 0x84; table[i] = sign ? -magnitude : magnitude; } return table;})();// Mu-law encode lookup (maps (sample >> 7) & 0xFF -> exponent)// prettier-ignoreconst EXP_LUT = [ 0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3, 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,];const MULAW_BIAS = 0x84;const MULAW_CLIP = 32635;export function mulawDecodeSample(byte: number): number { return MULAW_DECODE_TABLE[byte & 0xff];}export function mulawEncodeSample(sample: number): number { const sign = (sample >> 8) & 0x80; if (sign !== 0) sample = -sample; if (sample > MULAW_CLIP) sample = MULAW_CLIP; sample += MULAW_BIAS; const exponent = EXP_LUT[(sample >> 7) & 0xff]; const mantissa = (sample >> (exponent + 3)) & 0x0f; return ~(sign | (exponent << 4) | mantissa) & 0xff;}export function mulawDecode(mulaw: Uint8Array): Int16Array { const pcm = new Int16Array(mulaw.length); for (let i = 0; i < mulaw.length; i++) { pcm[i] = MULAW_DECODE_TABLE[mulaw[i]]; } return pcm;}export function mulawEncode(pcm: Int16Array): Uint8Array { const mulaw = new Uint8Array(pcm.length); for (let i = 0; i < pcm.length; i++) { mulaw[i] = mulawEncodeSample(pcm[i]); } return mulaw;}export function resample( input: Int16Array, fromRate: number, toRate: number,): Int16Array { if (fromRate === toRate) return input; const ratio = fromRate / toRate; const outputLength = Math.floor(input.length / ratio); const output = new Int16Array(outputLength); if (fromRate > toRate) { for (let i = 0; i < outputLength; i++) { const center = i * ratio; const start = Math.max(0, Math.floor(center)); const end = Math.min(input.length, Math.ceil(center + ratio)); let sum = 0; for (let j = start; j < end; j++) { sum += input[j]; } output[i] = Math.round(sum / (end - start)); } } else { for (let i = 0; i < outputLength; i++) { const srcIdx = i * ratio; const low = Math.floor(srcIdx); const high = Math.min(low + 1, input.length - 1); const frac = srcIdx - low; output[i] = Math.round(input[low] * (1 - frac) + input[high] * frac); } } return output;}export function wrapWav( pcm: Int16Array, sampleRate: number, channels = 1,): Buffer { const dataSize = pcm.length * 2; const header = Buffer.alloc(44); header.write("RIFF", 0); header.writeUInt32LE(36 + dataSize, 4); header.write("WAVE", 8); header.write("fmt ", 12); header.writeUInt32LE(16, 16); header.writeUInt16LE(1, 20); header.writeUInt16LE(channels, 22); header.writeUInt32LE(sampleRate, 24); header.writeUInt32LE(sampleRate * channels * 2, 28); header.writeUInt16LE(channels * 2, 32); header.writeUInt16LE(16, 34); header.write("data", 36); header.writeUInt32LE(dataSize, 40); const pcmBuf = Buffer.from(pcm.buffer, pcm.byteOffset, pcm.byteLength); return Buffer.concat([header, pcmBuf]);}export function parseWavHeader(wav: Buffer): { sampleRate: number; channels: number; bitsPerSample: number; dataOffset: number; dataSize: number;} { if (wav.length < 44) throw new Error("WAV too short"); let fmtFound = false; let sampleRate = 0; let channels = 0; let bitsPerSample = 0; let offset = 12; while (offset < wav.length - 8) { const chunkId = wav.toString("ascii", offset, offset + 4); const chunkSize = wav.readUInt32LE(offset + 4); if (chunkId === "fmt ") { channels = wav.readUInt16LE(offset + 10); sampleRate = wav.readUInt32LE(offset + 12); bitsPerSample = wav.readUInt16LE(offset + 22); fmtFound = true; } if (chunkId === "data" && fmtFound) { return { sampleRate, channels, bitsPerSample, dataOffset: offset + 8, dataSize: chunkSize, }; } offset += 8 + chunkSize; if (chunkSize % 2 !== 0) offset++; } return { sampleRate: wav.readUInt32LE(24), channels: wav.readUInt16LE(22), bitsPerSample: wav.readUInt16LE(34), dataOffset: 44, dataSize: wav.readUInt32LE(40), };}export function extractPcmFromWav(wav: Buffer): { pcm: Int16Array; sampleRate: number;} { const info = parseWavHeader(wav); if (info.bitsPerSample !== 16) { throw new Error(`Unsupported WAV bits per sample: ${info.bitsPerSample}`); } const end = Math.min(info.dataOffset + info.dataSize, wav.length); const slice = wav.subarray(info.dataOffset, end); const pcm = new Int16Array( slice.buffer, slice.byteOffset, Math.floor(slice.byteLength / 2), ); return { pcm, sampleRate: info.sampleRate };}export function computeMulawEnergy(mulaw: Buffer): number { if (mulaw.length === 0) return 0; let sumSq = 0; for (let i = 0; i < mulaw.length; i++) { const sample = MULAW_DECODE_TABLE[mulaw[i]]; sumSq += sample * sample; } return Math.sqrt(sumSq / mulaw.length);}export function mulawToWav16k(mulawBuf: Buffer): Buffer { const mulaw = new Uint8Array(mulawBuf); const pcm8k = mulawDecode(mulaw); const pcm16k = resample(pcm8k, 8000, 16000); return wrapWav(pcm16k, 16000);}export function mulawChunkToPcm16kBase64(mulawChunk: Buffer): string { const pcm8k = mulawDecode(new Uint8Array(mulawChunk)); const pcm16k = resample(pcm8k, 8000, 16000); return Buffer.from( pcm16k.buffer, pcm16k.byteOffset, pcm16k.byteLength, ).toString("base64");}export function wavToMulaw8k(wav: Buffer): Uint8Array { const { pcm, sampleRate } = extractPcmFromWav(wav); const pcm8k = resample(pcm, sampleRate, 8000); return mulawEncode(pcm8k);}export interface PcmS16leStreamState { leftover: Uint8Array<ArrayBufferLike>; headerBuffer: Uint8Array<ArrayBufferLike>; headerProcessed: boolean;}export function createPcmS16leStreamState(): PcmS16leStreamState { return { leftover: new Uint8Array(0), headerBuffer: new Uint8Array(0), headerProcessed: false, };}function concatUint8Arrays( a: Uint8Array<ArrayBufferLike>, b: Uint8Array<ArrayBufferLike>,): Uint8Array<ArrayBufferLike> { if (a.length === 0) return new Uint8Array(b); if (b.length === 0) return new Uint8Array(a); const combined = new Uint8Array(a.length + b.length); combined.set(a, 0); combined.set(b, a.length); return combined;}export function pcmS16leChunkToMulaw8k( base64Pcm: string, fromRate: number, state: PcmS16leStreamState,): { mulaw: Uint8Array; state: PcmS16leStreamState } { let pcmBytes: Uint8Array<ArrayBufferLike> = new Uint8Array( Buffer.from(base64Pcm, "base64"), ); if (!state.headerProcessed) { const headerBuffer = concatUint8Arrays(state.headerBuffer, pcmBytes); if (headerBuffer.length < 4) { return { mulaw: new Uint8Array(0), state: { ...state, headerBuffer }, }; } const isWavHeader = headerBuffer[0] === 0x52 && headerBuffer[1] === 0x49 && headerBuffer[2] === 0x46 && headerBuffer[3] === 0x46; if (isWavHeader) { if (headerBuffer.length < 44) { return { mulaw: new Uint8Array(0), state: { ...state, headerBuffer }, }; } try { const wavHeader = parseWavHeader(Buffer.from(headerBuffer)); if (headerBuffer.length < wavHeader.dataOffset) { return { mulaw: new Uint8Array(0), state: { ...state, headerBuffer }, }; } pcmBytes = headerBuffer.subarray(wavHeader.dataOffset); } catch { return { mulaw: new Uint8Array(0), state: { ...state, headerBuffer }, }; } } else { pcmBytes = headerBuffer; } state = { leftover: state.leftover, headerBuffer: new Uint8Array(0), headerProcessed: true, }; } if (state.leftover.length > 0) { pcmBytes = concatUint8Arrays(state.leftover, pcmBytes); } const bytesPerSample = 2; const remainder = pcmBytes.length % bytesPerSample; let newLeftover: Uint8Array<ArrayBufferLike> = new Uint8Array(0); if (remainder !== 0) { newLeftover = new Uint8Array(pcmBytes.subarray(pcmBytes.length - remainder)); pcmBytes = pcmBytes.subarray(0, pcmBytes.length - remainder); } if (pcmBytes.length < bytesPerSample) { return { mulaw: new Uint8Array(0), state: { ...state, leftover: newLeftover }, }; } const sampleCount = pcmBytes.length / bytesPerSample; const int16 = new Int16Array(sampleCount); const pcmView = Buffer.from(pcmBytes); for (let i = 0; i < sampleCount; i++) { int16[i] = pcmView.readInt16LE(i * bytesPerSample); } const pcm8k = resample(int16, fromRate, 8000); const mulaw = mulawEncode(pcm8k); return { mulaw, state: { ...state, leftover: newLeftover }, };}
Step 4: Add local voice activity detection
Create vad.ts. This file wraps the Silero VAD ONNX model and runs it locally on the CPU via onnxruntime-node.Silero VAD is a lightweight voice activity detection model that takes a short window of audio and returns a probability between 0 and 1 indicating whether that window contains speech. In this project it serves two purposes:
Turn-boundary detection: While the server is listening, VAD probabilities decide when the caller has started speaking and when they have stopped. Once speech ends (probability drops below a threshold for long enough), the server commits the buffered STT audio and triggers a reply.
Barge-in detection: While the assistant is speaking, VAD probabilities detect whether the caller is trying to interrupt. If the probability exceeds a higher threshold for several consecutive frames, the server immediately clears Twilio’s playback buffer and switches back to listening.
The wrapper loads the ONNX model once and shares the session across all concurrent calls. Each call gets its own SileroVad instance with independent RNN hidden state so one caller’s audio never bleeds into another’s detection.
vad.ts
vad.ts
// Silero VAD wrapper for barge-in detection on Twilio 8kHz mulaw audio.//// Uses the Silero VAD ONNX model (v5) which natively supports 8kHz input// with 256-sample windows (32ms per frame). The model runs on CPU via// onnxruntime-node with <1ms inference per frame.import { InferenceSession, Tensor } from "onnxruntime-node";import { fileURLToPath } from "url";import { mulawDecode } from "./audio-convert";const SAMPLE_RATE = 8000;const WINDOW_SIZE = 256;const CONTEXT_SIZE = 32;let sharedSession: InferenceSession | null = null;let loadPromise: Promise<InferenceSession> | null = null;async function getSession(): Promise<InferenceSession> { if (sharedSession) return sharedSession; if (!loadPromise) { const modelPath = fileURLToPath( new URL("./silero_vad.onnx", import.meta.url), ); loadPromise = InferenceSession.create(modelPath, { interOpNumThreads: 1, intraOpNumThreads: 1, executionMode: "sequential", executionProviders: [{ name: "cpu" }], }).then((session) => { sharedSession = session; console.log("[VAD] Silero VAD model loaded"); return session; }); } return loadPromise;}export class SileroVad { private session: InferenceSession; private rnnState: Float32Array; private context: Float32Array; private inputBuffer: Float32Array; private sampleRateNd: BigInt64Array; private sampleBuf: Float32Array; private sampleBufLen = 0; private constructor(session: InferenceSession) { this.session = session; this.rnnState = new Float32Array(2 * 1 * 128); this.context = new Float32Array(CONTEXT_SIZE); this.inputBuffer = new Float32Array(CONTEXT_SIZE + WINDOW_SIZE); this.sampleRateNd = BigInt64Array.from([BigInt(SAMPLE_RATE)]); this.sampleBuf = new Float32Array(WINDOW_SIZE + 160); } static async create(): Promise<SileroVad> { const session = await getSession(); return new SileroVad(session); } static warmup(): Promise<void> { return getSession().then(() => {}); } resetState(): void { this.rnnState.fill(0); this.context.fill(0); this.sampleBuf.fill(0); this.sampleBufLen = 0; } async processMulawChunk(mulawChunk: Buffer): Promise<number | null> { const pcm = mulawDecode(new Uint8Array(mulawChunk)); for (let i = 0; i < pcm.length; i++) { this.sampleBuf[this.sampleBufLen++] = pcm[i] / 32767; } if (this.sampleBufLen < WINDOW_SIZE) { return null; } const prob = await this.infer(this.sampleBuf.subarray(0, WINDOW_SIZE)); const remaining = this.sampleBufLen - WINDOW_SIZE; if (remaining > 0) { this.sampleBuf.copyWithin(0, WINDOW_SIZE, this.sampleBufLen); } this.sampleBufLen = remaining; return prob; } private async infer(audioWindow: Float32Array): Promise<number> { this.inputBuffer.set(this.context, 0); this.inputBuffer.set(audioWindow, CONTEXT_SIZE); const result = await this.session.run({ input: new Tensor("float32", this.inputBuffer, [ 1, CONTEXT_SIZE + WINDOW_SIZE, ]), state: new Tensor("float32", this.rnnState, [2, 1, 128]), sr: new Tensor("int64", this.sampleRateNd), }); this.rnnState.set(result.stateN!.data as Float32Array); this.context = this.inputBuffer.slice(-CONTEXT_SIZE); return (result.output!.data as Float32Array).at(0)!; }}
┌──────────────────────────────────────────┐ │ Twilio Voice Agent Server │ ├──────────────────────────────────────────┤ │ Local: http://localhost:3001 │ │ TwiML: POST /twiml │ │ WebSocket: /media-stream │ ├──────────────────────────────────────────┤ │ Next steps: │ │ 1. ngrok http 3001 │ │ 2. Set Twilio webhook to /twiml │ │ 3. Call your Twilio number │ └──────────────────────────────────────────┘
Step 10: Expose the app and connect Twilio
In another terminal:
Shell
ngrok http 3001
Copy the https:// forwarding URL and configure your Twilio number:
Open the Twilio Console and select your phone number.
Under voice configuration, set the incoming call webhook to https://your-ngrok-domain/twiml.
Use HTTP POST.
Save the number configuration.
When the call comes in, Twilio will request /twiml, receive a <Connect><Stream> response, and open a bidirectional Media Stream back to your /media-stream endpoint.
Step 11: Call the number
Dial your Twilio number from any phone.The expected flow is:
Twilio connects the call and opens the WebSocket.
The server warms up STT, TTS, and VAD.
The assistant plays a short greeting.
The caller speaks.
Local VAD decides when the caller has stopped.
The server commits the buffered STT stream.
The chat model starts streaming a reply.
Completed sentences are sent immediately to TTS.
TTS audio is converted back to audio/x-mulaw and played to the caller.
If the caller interrupts, the server sends Twilio a clear event and starts listening again.
How the low-latency path works
This architecture stays fast because it avoids unnecessary waits:
caller audio streams into STT continuously instead of being uploaded after the turn.
turn detection happens locally with Silero VAD, so there is no extra network hop to decide when to process.
chat completions stream token by token.
TTS starts on each completed sentence instead of waiting for the full reply.
Twilio playback can be interrupted immediately with a clear event.
Tuning the voice experience
The behavior is mostly controlled by a few thresholds in media-stream.ts:
SPEECH_START_PROB.
SPEECH_END_PROB.
SILENCE_DURATION_MS.
MIN_SPEECH_MS.
BARGE_IN_PROB_THRESHOLD.
BARGE_IN_CONSECUTIVE_FRAMES.
If the assistant cuts in too often, raise the barge-in threshold or require more consecutive frames. If it waits too long after the caller stops, reduce the silence duration slightly.