A voice agent that listens, thinks, and speaks in real time: speech-to-text, an LLM, and text-to-speech, streamed over WebSockets. It’s the public companion to the Real-Time AI Voice Agents case study, and is designed to show how response time is measured, stage by stage, and what moves it.

Status: being rebuilt. This branch replaces the original Plivo + Google + OpenAI + Azure bot, which needed four accounts to run, with a pipeline that runs locally with no accounts and no API keys. Cloud providers stay available: each stage can be pointed at any provider with an API key. The plan, in order:

  1. Foundation (done): the reply pipeline, ordered playback, a per-turn timeline, provider interfaces, LLM providers, and tests.
  2. Local speech and barge-in (done): voice activity detection, speech-to-text, text-to-speech, hosted speech providers, and a conversation harness.
  3. Browser client (done): talk to it from a laptop microphone, and see each reply’s latency by stage.
  4. Phone calls (done): Plivo Audio Streams, compatible with the original bot’s Plivo setup, tested against a simulated call.
  5. Measurements (done): latency per stage on the test audio, and what changes it. See Measurements.

How a turn works

caller audio ─▶ endpointer ─▶ speech-to-text ─▶ LLM (streamed) ─▶ sentences ─▶ text-to-speech ─▶ audio, in order
               (Silero VAD)   (Moonshine)       (Ollama)                       (Kokoro)
  • The endpointer (src/speech/endpointer.js) decides when the caller has finished: after VAD_SILENCE_MS of silence (500 ms by default). Every turn pays that wait before anything else can start.
  • Speech-to-text transcribes the whole utterance once it ends.
  • The reply pipeline (src/pipeline/reply.js) streams the model’s tokens, cuts them into sentences as they arrive, synthesises each sentence as soon as it’s complete, and delivers the audio strictly in order.
  • The session (src/session.js) runs the conversation, and handles barge-in. When the caller starts speaking while the assistant is thinking or talking, it stops generation, synthesis, and playback, and cuts the assistant’s message in the history to what the caller actually heard. That way the next reply doesn’t assume they heard the rest.
  • Each turn has a timeline (src/pipeline/timeline.js) on one clock: end of speech, transcript, first token, first sentence, first audio, first audio sent, and playback done.

Run it

Requires Node.js 24 or newer, and Ollama with a model pulled:

ollama pull qwen2.5:3b
npm install
npm run models        # the local speech models, about 440 MB, checksums verified
npm start             # then open http://127.0.0.1:8080 and click "Start conversation"

Use headphones. The page asks the browser for echo cancellation, but without headphones the assistant may still hear itself through your microphone and interrupt itself. (Whether the browser cancels audio played through Web Audio varies; this hasn’t been tested with speakers here.)

The page shows each turn as it happens. Every reply gets a bar showing how long it took to start, split into stages: waiting for silence, speech-to-text, the model’s first token, the first sentence, and the voice.

The server listens on 127.0.0.1 only, and holds one conversation at a time (HOST, MAX_SESSIONS).

Other commands:

npm run converse        # a scripted spoken conversation on the test audio (see below)
npm run chat            # a text chat through the same reply pipeline
npm run check           # lint and tests (no network; the model tests run once the models are downloaded)
npm run check:browser   # the browser client end to end in headless Chrome (see below; add -- --record to test recording)
npm run check:phone     # a simulated Plivo phone call end to end (see below)

The conversation harness

npm run converse plays the caller test audio (test/audio/) into a session in real time, in 20 ms frames, and plays the replies on a simulated speaker in real time. It includes a barge-in: the caller interrupts the answer to the long question. It writes every turn’s timeline (turns.json) and a stereo recording, with the caller on the left and the assistant on the right (conversation.wav), under results/.

The test audio is synthetic: six caller lines spoken by Kokoro voices that differ from the assistant’s, generated by scripts/make-test-audio.js. It’s cleaner than a real caller on a real microphone (no noise, no hesitation), so transcription results on it are a best case. Nothing is played aloud, and the assistant’s audio isn’t fed back into the microphone, so the harness measures the pipeline, not room acoustics or echo.

Recording a demo

During a conversation, Record saves it to a file when you stop:

  • Both voices: your microphone and the assistant’s voice, mixed inside the page. A screen recorder can’t do this when you wear headphones, because it only hears the microphone.
  • Video too, if you allow it: it asks to share the tab, with this one preselected. Allow it and you get a video of the page with both voices (MP4 in Chrome and Safari, WebM in Firefox). Decline it and you get the audio alone.

The browser check below also records, and it confirms that both voices are in the file.

The browser check

npm run check:browser starts the server and opens the page in the installed Google Chrome, headless. Chrome uses a WAV file built from the test audio as its microphone, so no microphone or speakers are needed. The script clicks “Start conversation” and checks that:

  • microphone audio arrives;
  • the greeting and a reply play to the end, with playback progress reported back;
  • an interruption clears playback and is answered;
  • the latency panels appear.

It exercises the whole browser path: the audio worklets, the WebSocket protocol, and the page. Its first run found a bug that no unit test could have: the microphone worklet sent one frame and then nothing, because transferring a buffer to the page empties it.

How the browser talks to the server

One WebSocket per conversation, at /browser (src/transports/browser.js). Audio is binary, 16-bit little-endian mono; everything else is JSON.

Direction Message
browser → server binary microphone audio at 16 kHz, in 20 ms frames
browser → server {"type":"start"} the assistant speaks its greeting
browser → server {"type":"played","turn","index","samples","done"} how far a reply piece has played (about every 80 ms, and at its end)
server → browser binary one reply piece: a 12-byte header (turn, index, sample rate), then the samples
server → browser {"type":"clear"} stop playback now (barge-in)
server → browser ready, speech_start, transcript, reply_piece, interrupted, turn_end, stage_error events for the page

Two audio worklets do the real-time work on the browser’s audio thread (public/worklets.js):

  • The microphone worklet downsamples to 16 kHz and sends 20 ms frames.
  • The player worklet plays pieces in order, resampling each one, and reports its progress. That progress is how barge-in knows what you heard.

Phone calls (Plivo)

The same session also answers phone calls through Plivo Audio Streams (src/transports/plivo.js):

  • The answer URL returns a <Stream bidirectional="true" keepCallAlive="true"> element. It’s served at /plivo/answer, and also at /answer.xml, the original bot’s URL.
  • Plivo then streams the caller’s audio to /plivo (or /), and plays back what the server sends.

The defaults are what the original bot used on live calls:

  • a 16 kHz PCM stream (contentType="audio/x-l16;rate=16000");
  • replies sent as 8 kHz mu-law playAudio;
  • the stream URL taken from STREAM_URL.

So a Plivo application already set up for the original bot keeps working.

The rebuild adds things the original didn’t use. Each has a fallback:

Reply audio Each sentence goes out as playAudio messages of at most 16 KB of base64, as Plivo recommends. Plivo’s reference says replies must use the stream’s own format, but the original bot sent 8 kHz mu-law on a 16 kHz PCM stream and it played. PLIVO_PLAY_AUDIO=stream switches to the documented way.
Playback progress Each sentence is followed by a checkpoint, and Plivo answers with playedStream once it has played. If no playedStream arrives, a sentence counts as played once its length plus 1.5 s has passed, and a warning is logged once.
Barge-in clearAudio empties Plivo’s queue. Plivo doesn’t say how far into the current sentence the caller got, so the history keeps an estimate based on the time since that sentence started playing.
Stream format Read from the start message when it’s there. If it’s missing or unknown, the call goes on in the format the answer XML asked for, and the server doesn’t hang up.

Tested against a simulation, not a live call. test/plivo-simulator.js plays Plivo’s part as its reference documents it: start, 20 ms media frames, a queue for playAudio, playedStream at each checkpoint, and clearedAudio. It plays each playAudio in that message’s own format, as Plivo evidently did for the original bot.

The tests run calls against it:

  • on all three stream formats, with both reply settings;
  • in the original bot’s exact setup, with no format in the start message;
  • with checkpoints never confirmed;
  • through barge-in;
  • using the original URLs.

npm run check:phone runs a whole call in real time, with the real models, in the original bot’s setup. The caller’s test audio first goes through an 8 kHz mu-law “phone line”, as every call does:

  • the caller’s lines were transcribed correctly;
  • replies went out as 8 kHz mu-law, the largest payload exactly at the 16 KB limit;
  • clearAudio went out 440 ms after the interruption began.

What still needs a real call: Plivo’s own network delay, and whether a real call ever leaves out playedStream or the format in start. The fallbacks above cover both.

Using it with a Plivo number

As with the original bot, run the server, expose it with a tunnel, and point a Plivo application at it:

npm start                              # listens on 127.0.0.1:8080
ngrok http 8080                        # or: cloudflared tunnel --url http://127.0.0.1:8080

In the Plivo application, set the Answer URL (POST) to https://<tunnel host>/answer.xml. The stream URL in the XML is built from the tunnel’s host name (wss://<tunnel host>/plivo). Set STREAM_URL to use a different one.

PLIVO_STREAM_TOKEN (optional) adds a token to the stream URL, and stream connections without it are refused. That’s worth setting whenever the tunnel is public. Plivo also signs its requests (X-Plivo-Signature-V3); checking that signature isn’t implemented here.

Measurements

Recorded on 2026-11-16 with npm run measure. Setup:

  • Machine: Apple M4 Pro, 24 GiB, macOS 26.6.2, on mains power.
  • Software: Node 24.16.0, sherpa-onnx-node 2.0.1, Ollama 0.40.16 (qwen2.5:3b 357c53fb659c, llama3.2:3b a80c4f17acd5), commit 4f64999.
  • Model settings: temperature 0, seed 42.

Every variant ran the scripted conversation (five caller lines and one interruption) twice, interleaved. All the data, including every turn of every run, is in measurements/2026-11-16/.

Response time here means the time from the end of the caller’s speech to the first reply audio being handed to the transport. It doesn’t include the network, or the client’s playback buffer.

Change from the baseline Median response time, ms (range) Where the time went
none: 500 ms of silence ends a turn, sentence by sentence, Moonshine base, qwen2.5:3b, Kokoro float32 1,201 (946–1,783) waiting for silence 500, speech-to-text 50, first token 74, first sentence 109, voice 473
end of turn after 300 ms of silence 986 (747–1,589) waiting −200
end of turn after 800 ms of silence 1,506 (1,247–2,078) waiting +300
synthesise the whole reply at once 1,563 (1,249–2,384) voice 799, first sentence 155 (the whole reply)
synthesise clauses as well as sentences 1,199 (946–1,850) no change: none of qwen2.5:3b’s first sentences had a clause break late enough to split
Moonshine tiny for speech-to-text 1,193 (929–1,745) speech-to-text 34 instead of 50
Kokoro int8 for the voice 1,954 (1,352–3,499) voice 1,230
llama3.2:3b as the LLM 1,520 (1,237–2,338) voice 698: its first sentences are longer (median 11 words, up to 29)

Each stage’s figure is its own median, so the stages don’t add up exactly to the median total. In this batch, the medians of each variant’s two runs were within 35 ms of each other, and every reply was the same word for word in both runs. Differences much smaller than that are noise.

What moves response time on this setup:

  • Waiting for silence, and voicing the first sentence, are most of it. Speech-to-text (50 ms) and the model’s first token (74 ms) are small with local models.

  • The silence threshold moves the response time one for one. With 300 ms, no test line was cut off early: every transcript had the same words as with 500 ms, and only one line’s punctuation changed. But the test speech is synthetic and pauses less than people do, so this doesn’t show that 300 ms is safe with real callers.

  • What decides the voice stage is the length of the first piece of text. Synthesising the whole reply added about 360 ms.

    Clause chunking only helps when first sentences are long. A second batch measured llama3.2:3b with and without it, two runs each, interleaved. It ran on the same commit plus that variant’s definition, which is committed with the results (measurements/2026-11-16-llama-clause/):

    • The median dropped from 1,491 to 1,252 ms.
    • In the first run both variants gave identical replies, so the turns can be compared one to one. Clauses were faster on five of six turns, by 222 to 757 ms, and 22 ms slower on the sixth.
  • Smaller models aren’t automatically faster. Kokoro int8 made the voice stage 2.6 times slower (1,230 against 473 ms). Moonshine tiny saved 16 ms, but doubled the errors on phone-quality audio (see below).

Barge-in: in all 20 runs, the assistant’s audio stopped 400 to 440 ms after the caller started speaking. Most of that is the voice detector confirming speech: 250 ms of minimum speech, plus its 32 ms analysis windows.

What’s kept in the history matters to the next reply. In the second run of the llama-with-clauses variant, the interruption landed one word later. The history kept “Racing thoughts can be really frustrating when” instead of “…really frustrating”, and every later reply in that conversation came out different.

Word error rate on the six test lines (60 words), transcribing each line after the endpointer has cut it out:

Model 16 kHz 8 kHz mu-law (phone)
Moonshine base 1 error (2%) 2 errors (3%)
Moonshine tiny 2 errors (3%) 4 errors (7%)

Both models hear “Hi” as “I”. On phone audio, Moonshine base also added a “10.” in front of “How many minutes…”. Moonshine tiny wrote “3” for “three” (counted as an error, since the words are compared as written), and on phone audio wrote “O’kea” and “to-day”.

Limits of these numbers:

  • The caller audio is synthetic, so it’s cleaner than real speech.
  • There’s no network in the loop.
  • It’s one machine, with six turns per run.
  • A different computer, model, or voice will give different numbers. The method and the scripts carry over.

Providers

Every stage is chosen by configuration: environment variables or a .env file (see .env.example). With nothing set, everything runs locally.

Stage Local (default) Hosted, with an API key
LLM Ollama (qwen2.5:3b) OpenAI, or any OpenAI-compatible chat API (LLM_PROVIDER=openai-compatible); Claude (LLM_PROVIDER=anthropic)
Speech-to-text Moonshine base, English (sherpa-onnx) any OpenAI-compatible transcription API; Google Cloud Speech-to-Text
Text-to-speech Kokoro-82M v1.0, voice af_heart (sherpa-onnx) any OpenAI-compatible speech API; Azure AI Speech
End of turn Silero VAD (sherpa-onnx) n/a

Every hosted provider except Claude is a plain fetch call. Claude goes through Anthropic’s official SDK (@anthropic-ai/sdk).

The hosted providers are tested against local mock servers that use the request and response formats from each provider’s documentation. They haven’t been run against the live services in this repository (that needs keys), and their latency isn’t measured here.

Using OpenAI or Claude

Set the stage’s provider and key in .env. Everything else stays the same.

# OpenAI for the conversation (speech can stay local)
LLM_PROVIDER=openai-compatible
LLM_MODEL=gpt-4o-mini
LLM_API_KEY=your-openai-key

# Claude for the conversation
LLM_PROVIDER=anthropic
LLM_API_KEY=your-anthropic-key      # or set ANTHROPIC_API_KEY
# LLM_MODEL=claude-opus-5-5         # the default
# LLM_EFFORT=low                    # thinking depth: low, medium, high, xhigh, max

# OpenAI for speech too
STT_PROVIDER=openai-compatible
STT_API_KEY=your-openai-key
TTS_PROVIDER=openai-compatible
TTS_API_KEY=your-openai-key

Claude is used for the conversation only, because Anthropic has no speech-to-text or text-to-speech API. A few settings work differently with it:

  • Thinking: it can’t be turned off on Claude Opus 5.5. LLM_EFFORT sets how much Claude thinks, and the default is low, because a spoken reply is a few sentences of conversation.
  • Maximum reply length: thinking counts towards it, so the default is 16,000 tokens.
  • Sampling settings: LLM_TEMPERATURE and LLM_SEED are ignored, because current Claude models reject them.
  • Declined requests: if Claude declines a request, the API retries it on a fallback model chosen for the reason (Anthropic’s server-side fallbacks).

Ollama is called through its native API rather than its OpenAI-compatible one, because only the native API accepts the context length (LLM_NUM_CTX). Without it, a long conversation is cut to the server’s default context, with no error.

Licences of the local models

Model Licence Notes
Silero VAD MIT
Moonshine base and tiny, English MIT Moonshine’s non-English models are under a non-commercial licence; only English is used here.
Kokoro-82M v1.0 Apache-2.0 Through sherpa-onnx 2.0, which pronounces words from a dictionary instead of the GPL-licensed espeak-ng.
sherpa-onnx (sherpa-onnx-node) Apache-2.0 Prebuilt for macOS and Linux (x64 and arm64) and Windows.

Avoided: LiveKit’s turn-detector model (its licence restricts it to LiveKit), TEN VAD (licence restrictions), and Piper voices with research-only or non-commercial licences.

What building it turned up

The local voice silently skips words it can’t pronounce. sherpa-onnx 2.0 replaced espeak-ng with a pronunciation dictionary (178,401 English words), and any word that isn’t in the dictionary is left out of the audio with only a log line. In testing it skipped:

  • digits, $25, 20% and 9:30;
  • acronyms (API, URL);
  • possessive names (Smith's);
  • regular forms of common words, such as opens, opened, wants, wanted and emails (the dictionary has open and opening).

Kokoro’s own text frontend derives those endings from the base word, but the dictionary lookup doesn’t. The local provider now does three things:

  • writes numbers, money, percentages and times as words (src/speech/normalize.js);
  • adds the missing -s, -ed and -ing forms, using the same US suffix rules as Kokoro’s frontend (483,797 derived entries, written once to a second dictionary file: src/speech/lexicon.js);
  • spells out unknown acronyms and reads possessives as plurals.

Words that are still unknown (Ollama, for example) are reported with each sentence instead of disappearing unnoticed.

The smaller Kokoro model is the slower one on this Mac. On an Apple M4 Pro CPU, the int8 model synthesised a short sentence (1.9 s of audio) in 1,000 to 1,200 ms at every thread count from 1 to 6. The float32 model took about 730 ms with 2 threads, 450 ms with 4, and 350 ms with 6. Selecting sherpa-onnx’s CoreML provider instead of the CPU made no difference to the float32 time. Those were exploratory runs on battery, used to choose the default (float32, 4 threads). In the recorded measurements, int8 made the voice stage 2.6 times slower (Measurements).

The voice detector starts segments late. On the test audio, the Silero segments began up to 350 ms after the speech did, and the transcript lost its first word (“Hi”, “Can you”). The endpointer now keeps a ring buffer of recent audio and starts each utterance 300 ms (VAD_PREROLL_MS) before the detected start.

The original bot played audio out of order. It sent each sentence’s audio as soon as that sentence’s synthesis finished, so a long first sentence followed by a short second one was played second-then-first. scripts/reproduce-original-ordering-bug.cjs reproduces it on the original code (commit f1b77c0):

LLM order:  "Sure, I can book that appointment for you on Tuesday morning at the downtown clinic." -> "Anything else today?"
sent order: "Anything else today?" -> "Sure, I can book that appointment for you on Tuesday morning at the downtown clinic."
OUT OF ORDER (bug reproduced)

Now each sentence’s synthesis is queued in order as soon as it starts, and delivery waits for the sentences before it. The same scenario is the regression test in test/ordering.test.js.

Licence

MIT.

From the repository's README on GitHub, synced Nov 16, 2026.

← All work